【问题标题】:How to implement database resiliency while having a scoped Dbcontext in EF Core?如何在 EF Core 中具有范围 Dbcontext 时实现数据库弹性?
【发布时间】:2021-03-10 22:02:18
【问题描述】:

根据 CQRS 模式,我有一个简单的命令,如下所示:

public sealed class EditPersonalInfoCommandHandler : ICommandHandler<EditPersonalInfoCommand> {

        private readonly AppDbContext _context;

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

        public Result Handle(EditPersonalInfoCommand command) {
            var studentRepo = new StudentRepository(_context);
            Student student = studentRepo.GetById(command.Id);
            if (student == null) {
                return Result.Failure($"No Student found for Id {command.Id}");
            }

            student.Name = command.Name;
            student.Email = command.Email;

            _context.SaveChanges();
            return Result.Success();
        }

}

现在我需要尝试_context.SaveChanges() 最多 5 次,如果它因异常而失败。为此,我可以简单地在方法中有一个 for 循环:

for(int i = 0; i < 5; i++) {
    try {
        //required logic
    } catch(SomeDatabaseException e) {
        if(i == 4) {
           throw;
        }
    }
}

要求是将方法作为单个单元执行。问题是一旦_context.SaveChanges() 抛出异常,就不能使用相同的_context 重新尝试逻辑。文档说:

丢弃当前的 DbContext。 创建一个新的 DbContext 并从数据库中恢复应用程序的状态。 通知用户上一次操作可能没有成功完成。

但是,在Startup.cs 中,我将AppDbContext 作为作用域依赖项。为了重新尝试方法逻辑,我需要一个 AppDbContext 的新实例,但注册为作用域不允许这样做。

我想到的一个解决方案是使AppDbContext 瞬态。但我有一种感觉,通过这样做,我将为自己打开一整套新问题。谁能帮帮我?

【问题讨论】:

  • 确切的例外是什么?
  • @mjwills DbUpdateException 在 _context.SaveChanges() 失败时抛出。

标签: c# asp.net-core dependency-injection ef-core-5.0 resiliency


【解决方案1】:

在保存上下文时至少有太多种类的错误。第一个发生在命令执行期间。第二个发生在提交期间(这种情况很少发生)。 即使数据已成功更新,也可能发生第二个错误。所以你的代码只处理第一种错误,而没有考虑第二种错误。

对于第一种错误,您可以在命令处理程序中注入 DbContext 工厂或直接使用IServiceProvider。这是一种反模式,但在这种情况下我们别无选择,就像这样:

readonly IServiceProvider _serviceProvider;
public EditPersonalInfoCommandHandler(IServiceProvider serviceProvider) {
        _serviceProvider = serviceProvider;
}

for(int i = 0; i < 5; i++) {
  try {
    using var dbContext = _serviceProvider.GetRequiredService<AppDbContext>();
    //consume the dbContext
    //required logic
  } catch(SomeDatabaseException e) {
    if(i == 4) {
       throw;
    }
  }
}

然而,正如我所说,要处理这两种错误,我们应该在 EFCore 中使用所谓的IExecutionStrategyhere 介绍了几个选项。但我认为以下最适合您的情况:

public Result Handle(EditPersonalInfoCommand command) {
    var strategy = _context.Database.CreateExecutionStrategy();
    
    var studentRepo = new StudentRepository(_context);
    Student student = studentRepo.GetById(command.Id);
    if (student == null) {
        return Result.Failure($"No Student found for Id {command.Id}");
    }

    student.Name = command.Name;
    student.Email = command.Email;
    const int maxRetries = 5;
    int retries = 0;
    strategy.ExecuteInTransaction(_context,
                                  context => {
                                      if(++retries > maxRetries) {
                                         //you need to define your custom exception to be used here
                                         throw new CustomException(...);
                                      }
                                      context.SaveChanges(acceptAllChangesOnSuccess: false);
                                  },
                                  context => context.Students.AsNoTracking()
                                                    .Any(e => e.Id == command.Id && 
                                                              e.Name == command.Name &&
                                                              e.Email == command.Email));

    _context.ChangeTracker.AcceptAllChanges();
    return Result.Success();
}

请注意,我假设您的上下文通过属性Students 公开了DbSet&lt;Student&gt;。 如果您有任何其他与连接无关的错误,IExecutionStrategy 将不会处理它,这很有意义。因为那是您需要修复逻辑的时候,所以重试数千次将无济于事,并且总是以该错误告终。这就是为什么我们不需要关心最初抛出的详细异常(在我们使用IExecutionStrategy 时不会暴露)。相反,我们使用自定义异常(如我上面的代码中所述)来通知由于某些与连接相关的问题而无法保存更改。

【讨论】:

  • 是否在ExecuteInTransaction 内部为每次重试创建新的context(考虑到context 仍作为范围依赖添加)?还有返回AsNoTracking()的任何具体原因?
  • @NavjotSingh ExecuteInTransaction 会为您服务,这里使用相同的上下文(每次重试都不会创建新实例),因为我们不使用工厂作为使用 @ 的第一种方法987654335@。使用AsNoTracking 以获得仅查询数据的最佳性能(这里查询验证更新是否成功)。
猜你喜欢
  • 2018-11-20
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-05
相关资源
最近更新 更多