Reputation: 51
I'm trying to implement a way to have multiple databases (identical databases, all have same tables etc.) but I need them to be separate thus multiple DBs. Is there a way to have a single DBContext and repository pattern that can interact with all of them (who have different connection strings) from the controller.
(all the DBs are the same just different DB name)
Ex. I have 3 controllers/endpoints api/course1
, api/course2
, and api/course3
Each course has a database. I've been looking at various documentation but having difficulty on how I can have it done with a repository pattern.
Thank you!
Upvotes: 0
Views: 402
Reputation: 4502
Yes, you can use different connection strings based on current request.
In your startup.cs, change the code to configure DbContext
to something similar to this example:
services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
{
var httpContext = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
var routeData = httpContext.GetRouteData();
string connectionString;
// insert here code to determine connection string based on route data.
options.UseSqlServer(
connectionString
);
});
Here I am using Dependency Injection to get information about current request and route data to determine the connection string. You can use any service you want and any logic you want to determine the connectionString.
Then when the ApplicationDbContext is injected in your repository class or your controller it will use that connection string for that request.
Upvotes: 1