使用时如何配置EntityFrameworkCore的DbContext NInject

How to configure DbContext of EntityFrameworkCore when using NInject

在.net core启动的ConfigureServices中class可以配置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,所以上面的方法不起作用。它不是 public 构造函数。

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

The problem is I cannot newup DbContextOptions and so the above does not work. Its not a public ctor.

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

例如

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

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

    //get options
    var options = optionsBuilder.Options;

    return options;
}

引用Configuring DbContextOptions