VivekDev
VivekDev

Reputation: 25349

How to configure DbContext of EntityFrameworkCore when using NInject

In the ConfigureServices of .net core startup class you can configure dbcontext as follows.

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

    services.AddMvc();
}

How do I configure this, if I use NInject or may be Autofac?

With NInject, I tried the following.

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

with GetDbContextOptionsForCurrentRequest defined as follows.

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

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

How do I go about using NInject or Autofac and configure EF Core DbContext?

Upvotes: 1

Views: 694

Answers (1)

Nkosi
Nkosi

Reputation: 247018

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

Build up the options using the options builder. That is what it is for as DbContextOptions is not designed to be directly constructed in your application code.

For example

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

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

    //get options
    var options = optionsBuilder.Options;

    return options;
}

Reference Configuring DbContextOptions

Upvotes: 2

Related Questions