Wie überprüfe ich, ob DbContext eine Transaktion hat?
Background: Ich habe einen WCF-Dienst mit SimpleInjector als IoC, der eine Instanz von DbContext pro WCF-Anforderung erstellt.
Backend selbst ist CQRS. CommandHandler haben eine Menge Dekoratoren (Validierung, Autorisierung, Protokollierung, einige gemeinsame Regeln für verschiedene Handlergruppen usw.) und einer von ihnen ist 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;
}
}
}
}
Problem tritt auf, wenn ein Befehl versucht, einen anderen Befehl innerhalb derselben WCF-Anforderung in einer Kette auszuführen. Ich habe eine erwartete Ausnahme in dieser Zeile erhalten:
using (var transaction = _context.Database.BeginTransaction())
, weil meine DbContext-Instanz bereits eine Transaktion hat.
Gibt es eine Möglichkeit, die Existenz der aktuellen Transaktion zu überprüfen?