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

4
我创建了一个名为App.Data的项目,其中包含领域对象和实现IDbContextFactory<T>接口的基类,用于创建DbContext。代码可在此处获取。
在单独的程序集中生成迁移非常有效。
我希望能够利用我在App.Data.Sql中创建的上下文,该上下文通过SqlDbContextFactory<MyAppDbContext>在注册实体框架时在asp.net mvc中创建。
我想要的是像这样的东西:
services.AddEntityFrameworkSqlServer()
.AddDbContext(typeof(SqlDbContextFactory<MyAppDbContext>))

将其注册为单例并不起作用,因为当解析时会抱怨没有配置提供程序。
services.AddSingleton<IDbContextFactory<..>, SqlDbContextFactory<..>>();
services.AddScoped<MyApp..>(p => p.GetRequiredService<IDb..>().Create());
1个回答

2

不要使用.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(...);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接