How do I add a DbContext instance to the IHostedService?

Question

How should I inject (using standard dependency injection) an instance DbContextin IHostedService?

What i tried

Currently, my class IHostedServiceaccepts an instance MainContext(output from DbContext) in the constructor.

When I launch the application, I get:

You cannot use the limited service "Microsoft.EntityFrameworkCore.DbContextOptions" from a singleton "Microsoft.Extensions.Hosting.IHostedService".

So, I tried to make a transition period DbContextOptionsby indicating:

services.AddDbContext<MainContext>(options => 
                options.UseSqlite("Data Source=development.db"), ServiceLifetime.Transient);

in my class Startup.

, , Github, DbContextOptions , AddDbContext.

singleton, concurrency (- , ).

+23
3

, . /db .. , . , DbContexts (EF Core 2.0 DbContext).

, IServiceScopeFactory , . , . , (, , , , db, ).

public class MyHostedService : IHostedService
{
    private readonly IServiceScopeFactory scopeFactory;

    public MyHostedService(IServiceScopeFactory scopeFactory)
    {
        this.scopeFactory = scopeFactory;
    }

    public void DoWork()
    {
        using (var scope = scopeFactory.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
        }
    }
}
+46

- , :

InvalidOperationException: 'x'

:

var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();

, :

var dbContext = (MyDbContext)scope.ServiceProvider.GetRequiredService<IMyDbContext>();
0

All Articles