【问题标题】:Facing threading issue in DbContext in a Blazor + CQRS architecture在 Blazor + CQRS 架构中面临 DbContext 中的线程问题
【发布时间】:2020-08-03 05:56:59
【问题描述】:

在我的项目中,我面临着著名的“在前一个操作完成之前在此上下文上启动了第二个操作”错误。

我知道它发生的原因,因为我在 Razor 页面上调用相同的方法 (GetPersons()) 来加载四个 ComboBox。这是我的基础设施/数据->上下文:

public class PlaygroundBiRepository : IPlaygroundBiRepository
{

    private readonly PlaygroundBiContext _context;

    public PlaygroundBiRepository(PlaygroundBiContext context) => _context = context;

    #region Person

    public async Task<Person> GetPersonByIdAsync(int id) => await _context.Persons.FindAsync(id);
    public IQueryable<Person> GetPersons() => _context.Persons;
    public async Task<PersonRole> GetPersonRoleByIdAsync(int id) => await _context.PersonRoles.FindAsync(id);

    public IQueryable<PersonRole> GetPersonRoles() => _context.PersonRoles;
    public async Task<Role> GetRoleByIdAsync(int id) => await _context.Roles.FindAsync(id);
    public IQueryable<Role> GetRoles() => _context.Roles;

    # endregion
}

在这里和那里阅读之后,我认为没有简单的解决方法。如果我想每次调用都使用一个新的,我将不得不丢失上下文中的 DI。

ServiceLifetime.Transient 不起作用,调用链不是async

请指点。

【问题讨论】:

标签: entity-framework-core cqrs blazor-server-side clean-architecture


【解决方案1】:

例外,看起来同一个上下文实例或同一个 DbConnection 可能被多个线程同时使用。然而,这只是一个猜测。

我有类似的问题,它是由AddDbContextPool引起的,将其更改为AddDbContext后解决了

【讨论】:

  • 你的猜测是正确的。然而,这不是我的解决方案。我已经在使用AddDbContext
  • 是存储库实例也是 Scoped 生命周期和所有使用 await 的异步调用
  • 我没有提到明确的范围,问题在于 public IQueryable&lt;Person&gt; GetPersons() =&gt; _context.Persons; 不能写成异步
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 2021-08-01
  • 2020-10-19
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多