CodexBloom - Programming Q&A Platform

implementing Dependency Injection Scope in ASP.NET Core with MediatR and Entity Framework Core

👀 Views: 199 💬 Answers: 1 📅 Created: 2025-06-12
asp.net-core mediatr entity-framework-core dependency-injection csharp

I've been banging my head against this for hours. I'm currently developing an ASP.NET Core 6 application where I'm using MediatR for handling commands and queries, along with Entity Framework Core for data access. I have registered my DbContext and MediatR services in the `Startup.cs` like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<MyCommandHandler>()); } ``` However, I'm running into a question with the scope of the DbContext. When I send a command that modifies the database through MediatR, I occasionally receive the behavior: `InvalidOperationException: The DbContext has been disposed and want to be used for the operation.` This seems to happen sporadically, especially under load. In my command handler, I'm doing something like this: ```csharp public class MyCommandHandler : IRequestHandler<MyCommand, MyResponse> { private readonly MyDbContext _context; public MyCommandHandler(MyDbContext context) { _context = context; } public async Task<MyResponse> Handle(MyCommand request, CancellationToken cancellationToken) { // Perform some database operations var entity = new MyEntity { Name = request.Name }; await _context.MyEntities.AddAsync(entity, cancellationToken); await _context.SaveChangesAsync(cancellationToken); return new MyResponse { Success = true }; } } ``` I ensured that all my commands are being sent asynchronously, and I’ve verified that my command handlers have a proper lifetime scope. I’m a bit confused about how the scope works in relation to MediatR and EF Core. Could this be a result of improper scoping, or might it be an scenario with how I'm using the MediatR pipeline? I've tried using `AddScoped` in various configurations and even tried using `AddTransient`, but the scenario continues. How can I ensure that the DbContext remains available for the duration of the command execution? Any insights would be greatly appreciated! For context: I'm using Csharp on Windows. I'd really appreciate any guidance on this.