As the title suggests, I am trying to inject a service into the MainLayout
page in Blazor Server-side. The service is an ApplicationDbContext being injected like this:
@inject ApplicationDbContext context
and being registered like this:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(
Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
However, I am getting an System.ObjectDisposedException
exception.
System.ObjectDisposedException: 'Cannot access a disposed object. A common cause of this error is disposing a context 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, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'ApplicationDbContext'.'
The first page load is OK, but after that, it raises this error. This also happens on any components nested within the layout page, but doesn't seem to happen on the pages themselves.
I resolved the problem by doing this.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(
Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
@inherits OwningComponentBase<ApplicationDbContext>
instead of
@inject ApplicationDbContext context
I hope this can help somebody. The ticket that discusses this issue is #10448 in the AspNetCore repository.