【问题标题】:How to configure DbContext of EntityFrameworkCore when using NInject使用 NInject 时如何配置 EntityFrameworkCore 的 DbContext
【发布时间】:2018-10-10 19:48:25
【问题描述】:

在.net core启动类的ConfigureServices中可以配置dbcontext如下。

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DotNetCoreT1DbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));

    services.AddMvc();
}

如果我使用 NInject 或者可能是 Autofac,我该如何配置?

使用 NInject,我尝试了以下方法。

kernel.Bind<DotNetCoreT1DbContext>().ToMethod(m => new DotNetCoreT1DbContext(GetDbContextOptionsForCurrentRequest()));

GetDbContextOptionsForCurrentRequest 定义如下。

private DbContextOptions GetDbContextOptionsForCurrentRequest()
{
   var options = new DbContextOptions();
   return options;
}

问题是我无法新建 DbContextOptions,因此上述方法不起作用。它不是公共演员。

如何使用 NInject 或 Autofac 并配置 EF Core DbContext?

【问题讨论】:

  • Ninject 没有任何直接的 ASP.NET Core 集成,因此您需要自己滚动它。至于 Autofac,有一个 official integration 可以让你替换内置的依赖注入容器,提供完全的兼容性。

标签: entity-framework asp.net-core ef-core-2.1


【解决方案1】:

问题是我无法新建 DbContextOptions,因此上述方法不起作用。它不是公共演员。

使用选项生成器构建选项。这就是它的用途,因为 DbContextOptions 并非旨在直接在您的应用程序代码中构造。

例如

private DbContextOptions GetDbContextOptionsForCurrentRequest() {
    var optionsBuilder = new DbContextOptionsBuilder<DotNetCoreT1DbContext>();

    //configure builder
    //optionsBuilder.Use*(...);

    //get options
    var options = optionsBuilder.Options;

    return options;
}

参考Configuring DbContextOptions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多