相关疑难解决方法(0)

如何检查DbContext是否有事务?

背景:我使用SimpleInjector作为IoC的WCF服务,它为每个WCF请求创建DbContext实例.

后端本身就是CQRS.CommandHandlers有很多装饰器(验证,授权,日志记录,不同处理程序组的一些通用规则等),其中一个是Transaction Decorator:

public class TransactionCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand> 
    where TCommand : ICommand
{
    private readonly ICommandHandler<TCommand> _handler;
    private readonly IMyDbContext _context;
    private readonly IPrincipal _principal;

    public TransactionCommandHandlerDecorator(ICommandHandler<TCommand> handler,
        IMyDbContext context, IPrincipal principal)
    {
        _handler = handler;
        _context = context;
        _principal = principal;
    }

    void ICommandHandler<TCommand>.Handle(TCommand command)
    {
        using (var transaction = _context.Database.BeginTransaction())
        {
            try
            {
                var user = _context.User.Single(x => x.LoginName == _principal.Identity.Name);
                _handler.Handle(command);
                _context.SaveChangesWithinExplicitTransaction(user);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当任何命令尝试链接在同一WCF请求中执行另一个命令时,会出现问题.我在这一行得到了一个预期的例外:

using (var …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework simple-injector

9
推荐指数
2
解决办法
6568
查看次数

标签 统计

c# ×1

entity-framework ×1

simple-injector ×1