EF Core DataContext with dotNet Framework 4.6.1 and Ninject

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

Question

I am adding EF Core 2.1.1 to a DotNet Framework 4.6.1 MVC 5 project that is using Ninject for dependency injection. I am would like to create a dbContext using dependency injection. I found this answer but it only shows how this can be done with the Microsoft dependency injection. I am wondering what the equivalent version of this is in Ninject, especially the part below:

services.AddDbContextPool<ExampleContext>(options => {
        options.UseSqlServer("_connectionstring_");
    });
1
1
8/9/2018 9:14:58 PM

Accepted Answer

In Ninject, wouldnt it just look something like

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

Allows you to set that up and call pretty happily you dbcontexts

1
8/9/2018 10:14:27 PM

Popular Answer

Another alternative is:

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");


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow