简体   繁体   中英

How to add background service which uses DBContecxt in ASP.NET core web API project

New to ASP. Created an application and everything(including db interactions) works fine, but my application should contain background services which are run on startup(and then work until manually stopped). It should have access 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 understand where and how I can get access 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM