dzenesiz
dzenesiz

Reputation: 1542

Cannot access a disposed object. Object name: 'IServiceProvider' error in AspNet Core/EF Core project

I am writing an ASP.NET Core application with Entity Framework Core. I'm also using MediatR.

When I trigger a database update, be it save or delete, I get this error:

Cannot access a disposed object. Object name: 'IServiceProvider'

It sometimes happens on the first try, sometimes on subsequent ones. I can't seem to find the pattern. What I did manage to do is hit the breakpoint in handler which calls await _applicationDbContext.SaveChangesAsync(cancellationToken); although the error actually gets thrown in controller, on await _mediator.Send(someRequestModel);. After the error gets thrown, the app goes in break mode and crashes.

I'll use dummy names, but this is the relevant code, I think:

Controller:

public MyController(IMediator mediator)
{
    _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
}

[HttpDelete("{id}")]
public async void Delete(string id)
{
    await _mediator.Send(new DeleteRequestModel(Guid.Parse(id))); // error thrown here
}

Handler:

public class DeleteCommandHandler : IRequestHandler<DeleteRequestModel>
{
    private readonly ApplicationDbContext _applicationDbContext;

    public DeleteCommandHandler(ApplicationDbContext applicationDbContext)
    {
        _applicationDbContext = applicationDbContext;
    }

    public async Task<Unit> Handle(DeleteRequestModel request, CancellationToken cancellationToken)
    {
        var item = _applicationDbContext.MyData.First(x => x.Id == request.Id);
        _applicationDbContext.MyData.Remove(item);

        await _applicationDbContext.SaveChangesAsync(cancellationToken); // pretty sure this errors out

        return Unit.Value;
    }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));
    services.AddDbContext<ApplicationAspNetUsersDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));

    services.AddDatabaseDeveloperPageExceptionFilter();

    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationAspNetUsersDbContext>();

    services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationAspNetUsersDbContext>();

    services.AddAuthentication()
        .AddIdentityServerJwt();
    services.AddControllers();
    services.AddRazorPages();
    // In production, the Angular files will be served from this directory
    services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; });

    services.AddSwaggerDocument();

    services.AddMediatR(AppDomain.CurrentDomain.Load("MySolution.MyProject.EntityFramework"));
    services.AddValidatorsFromAssembly(AppDomain.CurrentDomain.Load("MySolution.MyProject"));
    services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorPipelineBehavior<,>));

    services.AddSingleton(x =>
        new BlobServiceClient(Configuration.GetConnectionString("AzureBlobStorageConnection")));
    services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);

    services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
    services.Configure<AzureBlobStorage>(Configuration.GetSection("AzureBlobStorage"));
    services.Configure<ApplicationInsights>(Configuration.GetSection("ApplicationInsights"));
}

Finally, here is the stack trace, this time for update action:

at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at MediatR.Pipeline.RequestExceptionActionProcessorBehavior`2.GetActionsForException(Type exceptionType, TRequest request, MethodInfo& actionMethodInfo)
at MediatR.Pipeline.RequestExceptionActionProcessorBehavior`2.<Handle>d__2.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MediatR.Pipeline.RequestPostProcessorBehavior`2.<Handle>d__2.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MediatR.Pipeline.RequestPreProcessorBehavior`2.<Handle>d__2.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)   
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at MySolution.Web.Controllers.MyController.< Patch >d__7.MoveNext() in
..\Controllers\MyController.cs:line 85

Any help is greatly appreciated.

Upvotes: 2

Views: 3899

Answers (1)

T. van Schagen
T. van Schagen

Reputation: 168

You are using an async void in your controller. Async void should only be used in specific scenarios, in this case you should be using a Task as the return type.

Upvotes: 9

Related Questions