Efcore: Multiple DbContexts, wrong DbContextOptions being injected.

Created on 20 Apr 2016  路  2Comments  路  Source: dotnet/efcore

I have multiple modules that run code on start up of my ASP.NET 5 RC 1 application. Each module needs to register its own DbContext. The modules are not aware of eachother. They run the following code to register their paritcular DbContext:-

  services.AddEntityFramework()
             .AddSqlServer()
             .AddDbContext<GcDbContext>(options => options.UseSqlServer(connectionString));

What I notice, when I place a break point in the constructor of a particular DbContext instance, is that the wrong DbContextOptions are being passed in:

 public GcDbContext(DbContextOptions options, ILogger<GcDbContext> logger)
        : base(options)
        {
            Logger = logger;         
            // The options here are ones registered for a different DbContext!
        }

I need to have the constructor for unit testing purposes.

Where am I going wrong!? :)

Most helpful comment

@dazinator you want to use the generic options type:

c# public GcDbContext(DbContextOptions<GcDbContext> options, ILogger<GcDbContext> logger) : base(options)

BTW we have improved the exception message in RC2 to give more info on this situation

All 2 comments

@dazinator you want to use the generic options type:

c# public GcDbContext(DbContextOptions<GcDbContext> options, ILogger<GcDbContext> logger) : base(options)

BTW we have improved the exception message in RC2 to give more info on this situation

Ahh bingo. Cheers!

Was this page helpful?
0 / 5 - 0 ratings