2

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_");
    });
Thomas927
  • 853
  • 1
  • 11
  • 19

2 Answers2

3

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

Gibbon
  • 2,633
  • 1
  • 13
  • 19
  • What you have works for ninject but how do I add the options to the context? I get an exception right now: `No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider.` – Thomas927 Aug 10 '18 at 14:37
  • using Microsoft.EntityFrameworkCore; public class YourDbContext: DbContext { public YourDbContext(DbContextOptions options) : base(options) { } } Once you have the dbcontext set up, you shouldnt need override OnConfigure for anything – Gibbon Aug 10 '18 at 15:37
  • Yeah, I got it now. I removed some code from my previous implementation to help validate the ninject context was working and that was the one throwing the error. D'oh. Thanks for the help. – Thomas927 Aug 10 '18 at 16:55
  • In a .net Core 2.0 should I add that kernel.Bind.ToSelf().WithConstructorArgument....... in startup.cs? or where exactly it needs to be added? – Joe Samraj Oct 07 '18 at 15:37
  • @JoeSamraj it would be in the startup .cs but it would require some modification - https://stackoverflow.com/questions/46693305/how-to-integrate-ninject-into-asp-net-core-2-0-web-applications. That question has a detailed answer on how to setup ninject when using .Net Core as it varies depending which version of Ninject you are using – Gibbon Oct 07 '18 at 18:41
0

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");
Jan Muncinsky
  • 4,282
  • 4
  • 22
  • 40