.AddDbContext
also allows you to configure it at the same time. Configuration can't work with the abstract type, since you have to pass a IDbContextOptionsBuilder<T>
into your DbContext, where T
is your concrete implementation.
However, you can use both together if you want to inject the abstract class.
services.AddDbContext<AppDbContextMySql>( /* configure it */);
services.AddDbContext<AppDbContextSqlServer>( /* configure it */);
services.AddScoped<AppDbContextContract>(p => p.GetRequiredService<AppDbContextMySql>());
services.AddScoped<AppDbContextContract>(p => p.GetRequiredService<AppDbContextSqlServer>());
Not using .AddDbContext
you'd need to write
var dbOptionsA = new DbContextOptionsBuilder<AppDbContextMySql>();
dbOptionsA.UseMySql(...);
services.AddSingleton(dbOptionsA);
var dbOptionsB = new DbContextOptionsBuilder<AppDbContextSqlServer>();
dbOptionsB.UseSqlServer(...);
services.AddSingleton(dbOptionsB);
services.AddScoped<AppDbContextContract,AppDbContextMySql>();
services.AddScoped<AppDbContextContract,AppDbContextSqlServer>();
Not so pretty, eh?
But if the configuration happens from outside, then yes. You could only have a single AppDbContextContract
, which accepts a IDbContextOptions<AppDbContextContract>
and configure this in a library. You'd still have to register IDbContextOptions<AppDbContextContract>
during startup somewhere.