Blazor 等待 ef core 完成请求

Roy*_*ris 0 c# entity-framework-core asp.net-core blazor

所以现在我得到了

Error: System.InvalidOperationException: A second operation was started on this context before a previous operation completed.
Run Code Online (Sandbox Code Playgroud)

因为blazor似乎不尊重当前的请求。

我正在做的是这样的:

FirstComponent.razor

@inject IService _service; // abstracted service that calls EF

<layout> // layout stuff here
  <SecondComponent /> // second blazor component
</layout>

@code {

  protected override async Task OnInitializeAsync()
  {
     var getSomething = await _service.OnInitializedAsync();
  }

}
Run Code Online (Sandbox Code Playgroud)

SecondComponent.razor

@inject IService _service; // abstracted service that calls EF

@code {

  protected override async Task OnInitializedAsync()
  {
     var getSomething = await _service.GetSomething();
  }

}
Run Code Online (Sandbox Code Playgroud)

因此,我将实体拆分为多个子组件以进行编辑。现在我有一个“父”组件来调用所有这些子组件。


编辑1

我的IService看起来像这样。

public interface IService
{
  public Task<Something> GetSomething();
}

internal class Service : IService
{
  private readonly SomethingRepository _repo;

  public Service(SomethingRepository repo)
  {
     _repo = repo;
  }

  public async Task<Something> GetSomething() => _repo.GetAsync();
}

internal SomethingRepository
{
  private readonly AppDbContext _context;

  public SomethingRepository(AppDbContext context)
  {
    _context = context;
  }

  public async Task<Something> GetAsync() => ...;//implementation of whatever
}
Run Code Online (Sandbox Code Playgroud)

我将我的服务添加AppDbContext到服务集合中,并将AddDbContext我的服务和存储库添加到AddScoped

Dav*_*oft 5

对于 Blazor Server 应用程序,您不应将现有的 DI 生命周期用于 DbContext。相反,为每个请求创建一个新请求,或将其范围限定为一个组件。每:

EF Core 为 ASP.NET Core 应用提供 AddDbContext 扩展,默认情况下将上下文注册为作用域服务。在 Blazor Server 应用中,范围服务注册可能会出现问题,因为实例是在用户电路内的组件之间共享的。DbContext 不是线程安全的,也不是为并发使用而设计的。由于以下原因,现有的生命周期是不合适的:

  • Singleton 在应用程序的所有用户之间共享状态并导致不适当的并发使用。
  • 作用域(默认值)在同一用户的组件之间带来了类似的问题。
  • 每个请求都会产生一个新实例的瞬态结果;但由于组件的寿命可能很长,这会导致上下文的寿命比预期的要长。

以下建议旨在提供在 Blazor 服务器应用程序中使用 EF Core 的一致方法。

  • 默认情况下,考虑每个操作使用一个上下文。。。。
  • 使用标志来防止多个并发操作: . 。。
  • 对于利用 EF Core 的更改跟踪或并发控制的寿命较长的操作,请将上下文范围限制在组件的生命周期内。

带有 Entity Framework Core (EFCore) 的 ASP.NET Core Blazor 服务器