将服务注入 Server-side Blazor 中的 MainLayout.cs

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

如标题所示,我正在尝试将服务注入 Blazor Server-side 中的 MainLayout 页面。该服务是一个像这样注入的 ApplicationDbContext:

@inject ApplicationDbContext context

并像这样注册:

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(
        Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);

但是,我遇到了 System.ObjectDisposedException 异常。

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'.'

第一个页面加载正常,但是之后,它引发了这个错误。这也会发生在布局页面中嵌套的任何组件上,但似乎不会发生在页面本身上。

我通过这样做解决了问题。

  1. 注册了 DbContext
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(
        Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
  1. 像这样 将 DbContext 注入到 嵌套的剃刀组件
@inherits OwningComponentBase<ApplicationDbContext>

而不是

@inject ApplicationDbContext context
  1. 执行了数据库操作,它神奇地起作用了。

我希望这可以帮助到一些人。讨论此问题的工单是 #10448 in the AspNetCore 存储库。