简体   繁体   English

将服务注入到服务器端 Blazor 中的 MainLayout.cs

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

As the title suggests, I am trying to inject a service into the MainLayout page in Blazor Server-side.正如标题所暗示的,我正在尝试将服务注入 Blazor 服务器端的MainLayout页面。 The service is an ApplicationDbContext being injected like this:该服务是一个像这样注入的 ApplicationDbContext:

@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异常。

System.ObjectDisposedException: 'Cannot access a disposed object. System.ObjectDisposedException: '无法访问已处理的对象。 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.如果您在上下文上调用 Dispose() 或将上下文包装在 using 语句中,则可能会发生这种情况。 If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.如果你使用依赖注入,你应该让依赖注入容器来处理上下文实例。 Object name: 'ApplicationDbContext' .'对象名称: “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.我通过这样做解决了这个问题。

  1. Registered the DbContext注册了 DbContext
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(
        Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
  1. Injected the DbContext into a nested razor component like this像这样将 DbContext 注入到嵌套的 razor 组件中
@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.讨论此问题的票证是AspNetCore存储库中的#10448

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM