Injecting services in to the MainLayout.cs in Server-side Blazor

blazor blazor-server-side c# dependency-injection entity-framework-core

Question

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.

1
1
12/7/2019 8:35:00 PM

Accepted Answer

I resolved the problem by doing this.

  1. Registered the DbContext
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(
        Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
  1. Injected the DbContext into a nested razor component like this
@inherits OwningComponentBase<ApplicationDbContext>

instead of

@inject ApplicationDbContext context
  1. Performed database operations and it magically worked.

I hope this can help somebody. The ticket that discusses this issue is #10448 in the AspNetCore repository.

0
12/7/2019 8:34:41 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow