带有dotNet Framework 4.6.1和Ninject的EF Core DataContext

时间:2018-08-09 21:14:58

标签: c# asp.net-mvc-5 entity-framework-core ninject

我正在将EF Core 2.1.1添加到使用Ninject进行依赖项注入的DotNet Framework 4.6.1 MVC 5项目中。我想使用依赖项注入创建dbContext。我找到了this answer,但它仅显示了如何使用Microsoft依赖项注入来完成。我想知道Ninject中有什么等效版本,尤其是下面的部分:

services.AddDbContextPool<ExampleContext>(options => {
        options.UseSqlServer("_connectionstring_");
    });

2 个答案:

答案 0 :(得分:1)

在Ninject中,它看起来就像

kernel.Bind<YourDbContextHere>.ToSelf().WithConstructorArgument("options", new DbContextOptionsBuilder<YourDbContextHere>().UseSqlServer("YourConnectionString").Options);

允许您进行设置并非常高兴地调用dbcontexts

答案 1 :(得分:0)

另一种选择是:

public class MyContext : DbContext
{
    private readonly string connectionString;

    public MyContext (string connectionString)
    {
        this.connectionString = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(this.connectionString);
    }
}

kernel.Bind<MyContext>.ToSelf().WithConstructorArgument("connectionString", "YourConnectionString");