如何在 EF Core 中具有作用域 Dbcontext 的同时实现数据库弹性?

问题描述

根据 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 变为瞬态。但是我有一种感觉,通过这样做,我将为自己打开一整套新问题。有人可以帮我吗?

解决方法

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

对于第一种错误,您可以将 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();
}

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...