背景:我使用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)