New to ASP. Created an application and everything(including db interations) works fine, but my application should contain background services wich are run on startup(and then work until manually stopped). It should have acess to dbcontext and ideally load data before any user input.
Seems like it should be created somewhere in ConfigureServices and run in Configure?
Don't really understand how to implement it cause dependency injections. The main problem - I don't unserstand where and how I can get acess to dbcontext. The only way I know is controllers, but it's obviously not the solution.
I know that 100% there is simple solution, but can't find it cause don't know what to search. Some kind of link on reference/microsoft docs should be enough.
CodePudding user response:
You should register your DbContext in ConfigureServices like so:
Host.CreateDefaultBuilder(args)
ConfigureServices((hostContext, services) =>
{
// Example to add SqlServer DB Context
string connectionString = //for example load connection string from config
services.AddDbContext<MyDbContext>(o => o.UseSqlServer(connectionString);
}
After registering your context like this, you are able to inject it into your other services via constructor injection.
public class MyBackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
public MyBackgroundServcice(IServiceScopeFactory serviceScopeFactory)
{
_scopeFactory= serviceScopeFactory;
}
public MyData GetData()
{
using IServiceScope scope = _scopeFactory.CreateScope();
MyDbContext context = scope.ServiceProvider.GetService<MyDbContext>();
// Do something with context ...
}
}
Architecture wise I would also suggest implementing a service for your database layer that you can inject in your background services since managing DbContext scopes would be a lot cleaner like this.