Using DbContext in RabbitMQ Consumer (Singleton Service)

I have a singleton, RabbitMQ Singleton, which works fine, but has a service dependency with scope every time a message arrives:

consumer.Received += _resourcesHandler.ProcessResourceObject; //Scoped Service

My services are registered as follows:

services.AddScoped<IHandler, Handler>();
services.AddSingleton<RabbitMqListener>();

Limited service constructors use DI for the Db context:

private readonly ApplicationDbContext _appDbContext;

public ResourcesHandler(ApplicationDbContext appDbContext)
{
    _appDbContext = appDbContext;
}

This namespace service calls a Db context to insert properties into the database when a message is received.

However, since the service with the scope has a different lifespan, the launch is not performed.

Is there a better way to do this? I could make the cloud service single, but then I would have a problem using DbContext as a dependency.

What is the “protocol” in DI for calling dbContext in single-user services?

using, , , DbContextOptions, DI. ?

+4
2

- . ​​asp.net , , . - rabbitmq HTTP-. , .

IServiceProvider RabbitMqListener ( _provider ), :

private void OnMessageReceived(Message message) {
    using (var scope = _provider.CreateScope()) {
        var handler = scope.ServiceProvider.GetRequiredService<IHandler>();
        handler.ProcessResourceObject(message);
    }
}

ApplicationDbContext factory ( ). factory ApplicationDbContext, . :

services.AddSingleton<Func<ApplicationDbContext>>(() =>
{
    var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
    optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    return new ApplicationDbContext(optionsBuilder.Options);
});

IHandler singleton ( , ), Func<ApplicationDbContext> :

private readonly Func<ApplicationDbContext> _appDbContextFactory;

public ResourcesHandler(Func<ApplicationDbContext> appDbContextFactory)
{
    _appDbContextFactory = appDbContextFactory;
}

, - :

using (var context = _appDbContextFactory()) {
    // do stuff
}
+4

, ContextFactory , .

Factory

services.AddSingleton<ContextFactory>();

.

: _yourService.GetContext(); .

Factory , . , , factory.

, Singleton, .

, , Transient, .

** : .

0

Source: https://habr.com/ru/post/1695966/


All Articles