Thomas927
Thomas927

Reputation: 913

EF Core DataContext with dotNet Framework 4.6.1 and Ninject

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

Upvotes: 2

Views: 1886

Answers (2)

Jan Muncinsky
Jan Muncinsky

Reputation: 4408

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

Upvotes: 0

Gibbon
Gibbon

Reputation: 2773

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

Upvotes: 3

Related Questions