在 Core Mvc 中使用 IDbContextFactory 注册 EF Core ASP.NET



我创建了一个项目App.Data,其中包含域对象和一个基类,该基类实现了用于创建DbContext IDbContextFactory<T>。代码可在此处获得。

在单独的程序集中生成迁移效果很好。

我想利用我在App.Data.Sql中创建的上下文,该上下文是在 SqlDbContextFactory<MyAppDbContext> 中注册 mvc asp.net 时

创建的。

我想要的是类似的东西

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(...);
});

最新更新