1

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?

1
  • 2
    Ninject does not have any direct ASP.NET Core integration, so you will need to roll it yourself. As for Autofac, there’s an official integration which allows you to replace the built-in dependency injection container, providing full compatibility. Commented Oct 10, 2018 at 11:01

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.