So imagine you want to access the multiple dbContexts that are on different environments or servers (Dev, Test, Pre-prod etc), and use the data from all those different databases to calculate something. How would I register multiple dbContexts of the same type (MonitoringDbContext) and differentiate between them?
This is where I got stuck
var envDbContextDetails = configuration.GetSection("EnvironmentConnectionStrings").Get<EnvironmentConnectionStringsModel>();
var nonRegisteredDbContexts = envDbContextDetails.DbConnectionStrings.Where(x => x.Environment != envDbContextDetails.CurrentDbEnvironment).ToList();
nonRegisteredDbContexts.ForEach(x => services.AddDbContext<MonitoringDbContext>(options => options.UseSqlServer(x.ConnectionString)));
So I'm registering multiple MonitoringDbContext contexts, and now what? My idea was to resolve, pull them and add them in a Dictionary<string, MonitoringDbContext> where the key is the environment name (Dev, Test etc) and use them from a DbContextFactory where I would select the one I need, or use all of them in a loop, depending on what I need to calculate. But I have no idea how to get the dbContexts after registering them, and how to differentiate between them.
You can register multiple instances of a service in the services collection, and get all of them by resolving
IEnumerable<T>where T is the type of your service.Knowing that, you should inspect the code of your library and check if registration of services do simple
Addin theIServiceCollection. EF Core use TryAddX, so just your first registration is included in the service collection. So we have to customize the registration.You can create a wrapper like that:
Then register the basics services EF Core needs to run:
Then foreach environment, register an EnvWrapper with an instance of your DbContext:
If you want, you can resolve
IEnumerable<Wrapper<MonitoringDbContext>>and iterate on the result:Maybe you should register
MonitoringDbContextStorein your service collection.If you want/need
IDbContextFactory, you can add more services:And per environment:
Again, you can resolve a collection of EnvWrapper with the type
IEnumerable<EnvWrapper<IDbContextFactory<MonitoringDbContext>>>.