我如何在Blazor Server中将服务注入实体框架adddbContextFactory lambda函数?
在Blazor Server中,如何将范围的服务注入下面的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);
});
In Blazor server, how can I inject a scoped service into the lambda below so that I can read the authenticated user and select a SQL connection string based on the user.
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);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下 this IDE因此可能包含一些错别字):
Following this link, it should look something like this (I'm typing without IDE so it may contain some typos):
你不能那样做。 Services.Add ....只是将类/接口添加到集合中。直到后来,服务容器才开始初始化,直到您使用DI对象之前,该对象的实例才会初始化。
为了说明过程,这是测试中设置服务容器的代码。
无论您设计什么,都需要重新思考。在温泉会话初始化之前,您无法获得用户。
You can't do that. Services.Add.... simply adds classes/interfaces to a collection. It's not till later that the services container gets initialised, and until you use a DI object that an instance of that object gets initialised.
To illustrate the process, here's the code to set up a services container
serviceProvider
in a test.Whatever you design, it needs rethinking. You can't get a user until an SPA session has initialized.
AddDbContextFactory在Singleton上具有默认参数集。
添加 servicelifetime.scoped
AddDbContextFactory has a defaulted parameter set to Singleton.
add ServiceLifetime.Scoped