Blazor 在上一个操作完成之前在此上下文中启动了第二个操作

Blazor A second operation started on this context before a previous operation completed

我动态地制作了 NavMenu 并且 return 菜单由用户在数据库中并且在索引页面中我已经 return 在数据库中编辑了一些东西但是当我 运行 应用程序或重新加载它告诉我下面的错误

InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.

导航菜单代码,

List<Menu> menus = new List<Menu>();

protected override async Task OnInitializedAsync()
{ 
    menus  = await MenuService.GetMenus();

}

索引码

@if (priorities == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Name</th> 
            </tr>
        </thead>
        <tbody>
            @foreach (var priority in priorities)
            {
                <tr>
                    <td>@priority.Name</td>
                </tr>
            }
        </tbody>
    </table>
}

@code { 
    List<Priority> priorities;

    protected override async Task OnInitializedAsync()
    { 
        priorities = await PriorityService.GetPriorities();

    }
}

解决方案是使用`DbContextFactory :

Quoting docs:

Some application types (e.g. ASP.NET Core Blazor) use dependency injection but do not create a service scope that aligns with the desired DbContext lifetime. Even where such an alignment does exist, the application may need to perform multiple units-of-work within this scope. For example, multiple units-of-work within a single HTTP request.

In these cases, AddDbContextFactory can be used to register a factory for creation of DbContext instances. For example:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextFactory<ApplicationDbContext>(
        options =>
            options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test"));
}

我对 Blazor 服务器应用程序的解决方案是使 ApplicatonDbContext 和服务都成为 Transient:

services.AddDbContext<ApplicationDbContext>(x => x.UseSqlServer(connectionString), ServiceLifetime.Transient);
services.AddTransient<ICustomerService, CustomerService>();

仅当我尝试从多个控件中的同一服务访问用户信息时才出现此错误。有道理——它们在初始化时都在争夺相同的资源。

对我来说,解决方案不是改变范围——而是重新思考我真正在做什么——为什么有 2 个单独的控件试图访问同一用户的会员功能?