Asp.net core 如何在我的DbContext类中注入服务并使host.MigrateDatabase()仍在工作
我有一个正在运行的EFCore、.NET5、Blazor WASM应用程序。 我调用Asp.net core 如何在我的DbContext类中注入服务并使host.MigrateDatabase()仍在工作,asp.net-core,dependency-injection,entity-framework-core,dbcontext,Asp.net Core,Dependency Injection,Entity Framework Core,Dbcontext,我有一个正在运行的EFCore、.NET5、Blazor WASM应用程序。 我调用wait host.MigrateDatabase()以使我的数据库始终保持最新 public静态异步任务MigrateDatabase(此IHost主机) { 使用var scope=host.Services.CreateScope(); 尝试 { //使用DI获取所需的上下文工厂: var contextFactory=scope.ServiceProvider.GetRequiredService Use
wait host.MigrateDatabase()在myProgram.Main()中编写>以使我的数据库始终保持最新
public静态异步任务MigrateDatabase(此IHost主机)
{
使用var scope=host.Services.CreateScope();
尝试
{
//使用DI获取所需的上下文工厂:
var contextFactory=scope.ServiceProvider.GetRequiredService User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
public ClaimsPrincipal用户{get;set;}
}
我在StartUp中注册了这个类,如下所示:
services.AddScoped(sp=>
{
var context=sp.GetService()?.HttpContext;
var identityOptions=新identityOptions();
if(context?.User.Identity!=null&&context.User.Identity.IsAuthenticated)
{
identityOptions.User=context.User;
}
返回标识选项;
});
我将这个IdentityOptions
类注入到其他几个服务中,没有任何问题。
但是当我将它注入我的AppDbContext
时:
public-AppDbContext(DbContextOptions选项,IdentityOptions IdentityOptions)
:基本(选项)
{
...
}
我在MigrateDatabase()
中遇到错误:
“无法从根提供程序解析作用域服务“IdentityOptions”。
我在谷歌上找到了很多选择,但找不到适合我的解决方案。
请给我一些建议
更新:
services.AddDbContextFactory<AppDbContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection"),
b => b.MigrationsAssembly("DataAccess"))
#if DEBUG
.LogTo(Console.WriteLine, new [] {RelationalEventId.CommandExecuted})
.EnableSensitiveDataLogging()
#endif
);
services.AddDbContextFactory(
options=>options.UseSqlServer(Configuration.GetConnectionString(“DbConnection”),
b=>b.MigrationsAssembly(“数据访问”))
#如果调试
.LogTo(Console.WriteLine,新[]{RelationalEventId.CommandExecuted})
.EnableSensitiveDataLogging()
#恩迪夫
);
感谢@IvanStoev(再次)的大力帮助,我找到了答案。
在Startup
中向AddDbContextFactory
添加生存期:ServiceLifetime.Scoped
解决了我的问题。
现在,我可以在SaveChanges
中使用我的IdentityOptions类,并自动更新我的创建的*
和更新的*
属性。如何注册db上下文工厂?AddDbContextFactory
?生存期?(默认为Singleton)。谢谢Ivan的回复。我已经更新了我的问题。我使用了AddDbContextFactory
您是否尝试过不同的生存期,比如Scoped
(AddDbContextFactory
的最后一个可选参数)?我不是DI专家,但将Scoped注入单例听起来有问题(逻辑上)。如果这有帮助,请告诉我,否则您可能需要自己的IDbContextFactory
实现。但让我们先看看这个。是的,Ivan。添加lifetime:ServiceLifetime.Scoped
解决了我的问题。您能将其作为答案发布吗?我会接受它。很高兴它帮助mate。但正如我所说,我离DI很远,所以请随时发布和访问请给我一个自我回答(给未来的读者),我很乐意回答。