【发布时间】:2021-03-26 12:21:20
【问题描述】:
所以现在我得到了一个
Error: System.InvalidOperationException: A second operation was started on this context before a previous operation completed.
因为 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();
}
}
SecondComponent.razor
@inject IService _service; // abstracted service that calls EF
@code {
protected override async Task OnInitializedAsync()
{
var getSomething = await _service.GetSomething();
}
}
所以我将我的实体拆分为多个子组件进行编辑。现在我有了一个调用所有这些子组件的“父”组件。
编辑 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
}
我正在使用 AddDbContext 将我的 AppDbContext 添加到服务集合中,并使用 AddScoped 添加我的服务和存储库
【问题讨论】:
-
听起来您设置 EF 上下文的方式存在设计缺陷。问题出在您的服务上,这不是 Blazor 的错。您一次不能将同一个上下文实例用于多个操作。正确的依赖注入将确保每个请求都有自己的实例。
-
也就是说,目前阅读 docs blazor 不支持范围,就像您的 API 控制器或 MVC 控制器一样。所以我的问题是,如何更新 blazor 以确保我的组件仅在另一个完成调用后才调用数据库
-
请展示您的服务。
-
我会编辑我的答案,但我有一个非常大的项目,所以我会尝试抽象它,但不会遗漏核心功能。
-
如果服务在请求之间使用相同的上下文实例,这将是一个问题。 This is the preferred way 为 di 系统提供上下文。
标签: c# asp.net-core entity-framework-core blazor