I have an app with a common database requirement for an ASP.Net Core web app and an ASP.Net Core Worker service background task. I have a standard Repository pattern based approach with a class for each entity (standard CRUD operations).
My question concerns the best approach to manage the Db context injection into the Repository class for both apps. This is easy for the ASP.Net Core web app: Constructor based DI each time a Db context is required. However, the worker service requires obtaining a fresh Db context for every ExecuteAsync iteration, and passing it to each repository class by some means. This works, but is a bit messy:
code
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using var scope = _serviceScopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
...
}
}
code
I'm interested in a single Db data access point design pattern that will manage both apps while also getting thread-safe Db contexts when required.
Any help greatly appreciated
DbContext
, though, and "passing it to each repository class by some means" seems to be missing the point of DI. You only need to ask the container to create an instance of the highest-level type you need (e.g. a service of some sort, or perhaps a repository in your case), and if its dependency graph needsDbContext
s, the container will create scoped instances as needed. – sellotape