DbContext Management
Ali Shakkouf
ASP.NET Core Developer | Agile Development | Entity Framework, Web APIs, SQL Server
To manage multiple DbContexts dynamically, I implemented a factory-based approach. The IDbContextFactory interface allowed me to create instances of DbContext at runtime, passing the appropriate connection string for each tenant. Dependency injection was configured to ensure that each tenant gets its unique database context and I made sure to use same context within same request by using dictionary to store it.
The IDesignTimeDbContextFactory interface in Entity Framework Core serves a specific purpose? it provides a way to create DbContext instances at design time for tools like migrations or scaffolding.
This function is responsible for creating the dbcontext instance and to make sure if there is existed context instance to be used.
This function to implement the interface and this connection string is the one where the migrations would be executed.
And for each request I’ll create new dbContext according to database name (passed by header) in a generic provider like this :