在 Blazor 服務器中,如何將范圍服務注入到下面的 lambda 中,以便我可以讀取經過身份驗證的用戶并根據用戶選擇 SQL 連接字串。
builder.Services.AddDbContextFactory<GlueDbContext>((provider, options) =>
{
var AuthenticationStateProvider = provider.GetService<AuthenticationStateProvider>();
// *** Compiles but FAILS because AuthenticationStateProvider is not a Singleton ***
var user = _authenticationStateProvider.GetAuthenticationStateAsync().Result.User;
//
string sqlConnectString = SomeFunctionDerivingTheConnectionFromTheUser(user);
options.UseMySql(connectionString);
});
uj5u.com熱心網友回復:
在這個鏈接之后,它應該看起來像這樣(我在沒有 IDE 的情況下輸入,所以它可能包含一些拼寫錯誤):
var serviceScopeFactory = provider.GetService<IServiceScopeFactory>(); //IServiceScopeFactory is a singleton, so you can easily get it here
using var scope = serviceScopeFactory.CreateScope();
var authenticationStateProvider = scope.GetService<AuthenticationStateProvider>();
//...
uj5u.com熱心網友回復:
你不能那樣做。Services.Add.... 只是將類/介面添加到集合中。直到稍后,服務容器才會被初始化,直到您使用 DI 物件,該物件的實體才會被初始化。
為了說明這個程序,下面是在測驗中設定服務容器的代碼serviceProvider。
var services = new ServiceCollection();
services.AddDbContextFactory<InMemoryWeatherDbContext>(options => options.UseInMemoryDatabase("WeatherDatabase"));
services.AddSingleton<IDataBroker, ServerDataBroker>();
var serviceProvider = services.BuildServiceProvider();
無論你設計什么,都需要重新思考。在 SPA 會話初始化之前,您無法獲取用戶。
uj5u.com熱心網友回復:
AddDbContextFactory 有一個默認引數設定為 Singleton。添加ServiceLifetime.Scoped
builder.Services.AddDbContextFactory<GlueDbContext>((provider, options) =>
{
var AuthenticationStateProvider = provider.GetService<AuthenticationStateProvider>();
var user = _authenticationStateProvider.GetAuthenticationStateAsync().Result.User;
string sqlConnectString = SomeFunctionDerivingTheConnectionFromTheUser(user);
options.UseMySql(connectionString);
}, ServiceLifetime.Scoped);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/480065.html
