Sobes.tech
Senior

How to work with Scoped services (e.g., DbContext) inside Kafka/MassTransit consumer where there is no request scope?

sobes.tech AI

Answer from AI

In Kafka/MassTransit consumers, there is no built-in request scope, so Scoped services (e.g., DbContext) need to be created manually within the message handler.

This is usually done by injecting IServiceScopeFactory and creating a scope inside the consumer method:

public class MyConsumer : IConsumer<MyMessage>
{
    private readonly IServiceScopeFactory _scopeFactory;

    public MyConsumer(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    public async Task Consume(ConsumeContext<MyMessage> context)
    {
        using var scope = _scopeFactory.CreateScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();

        // Use dbContext for database operations
        // ...

        await dbContext.SaveChangesAsync();
    }
}

This approach ensures that Scoped services are created and disposed correctly for each message, avoiding lifecycle issues and resource leaks.