我创建了一个项目 App.Data
包含域对象和实现 IDbContextFactory<T>
的基类用于创建 DbContext
.代码可用 here .
在单独的程序集中生成迁移效果很好。
我想利用我在 App.Data.Sql
中创建的上下文这是通过 SqlDbContextFactory<MyAppDbContext>
创建的在 asp.net mvc 中注册 Entity Framework 时。
我想要的是类似的东西
services.AddEntityFrameworkSqlServer()
.AddDbContext(typeof(SqlDbContextFactory<MyAppDbContext>))
将其注册为单例不起作用,因为在解决时提示没有配置任何提供者。
services.AddSingleton<IDbContextFactory<..>, SqlDbContextFactory<..>>();
services.AddScoped<MyApp..>(p => p.GetRequiredService<IDb..>().Create());
最佳答案
代替 .AddDbContext(typeof(...))
提供一个工厂方法来创建上下文:
services.AddTransient(provider =>
{
//if needed: anything from DI
var bar = provider.GetService<TBar>();
//if needed: external captured variable
doSomething(service);
//explicit context creation
return new FooDbContext(...);
});
关于c# - 在 ASP.NET Core Mvc 中使用 IDbContextFactory 注册 EF Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44019968/