Context

The code block

public async void OnGet(int id)
{
    Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id);

    return Page();
}

Issue

This code will generate the following exception

System.ObjectDisposedException: 'Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

Reason

This exception will be thrown because the method return type is async void. In general, when using async void is bad, because:

  • You can't wait for its completion
  • Any unhandled exceptions will terminate the process

Solution

So return async Task instead of async void from the method as follows:

public async Task OnGet(int id)
{
    Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id);

    return Page();
}

Comments

Leave a Comment

All fields are required. Your email address will not be published.