I am implementing a webapi with ASP.NET Core 3.
On the back-end we have a number of company databases with the exact same schema/tables etc.
I am trying to implement a company database context provider that will let me resolve the correct company database context at runtime.
In my startup.cs I have the below code which should give you an idea what I'm trying to do:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CompanyDbContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("CompanyDbConnection")));
services.AddScoped<ICompanyRepository, CompanyRepository>();
services.AddDbContext<System.Func<CompanyType, ICompanyDbContext>>(dbContextOptionsBuilder => key =>
{
switch (key)
{
case CompanyType.HKG:
return dbContextOptionsBuilder.UseSqlServer(Configuration.GetConnectionString("HkgCompanyDbConnection"));
case CompanyType.SHG:
return dbContextOptionsBuilder.UseSqlServer(Configuration.GetConnectionString("ShgCompanyDbConnection"));
default:
throw new KeyNotFoundException();
}
});
//...
Instead of the generic CompanyContext
which will only have 1 connection I want to inject something like a service provider but for the dbcontexts into the CompanyRepository
constructor, which will then let me resolve different company dbcontexts in different cases in the repository functions (by passing arguments).
The idea is the last part of the code should return the correct context based on the key provided. But obviously the last part is not working. If it is not obvious the repository class will hold all the functions returning data from the database.
How would one go about this ?