Skip to content

Instantly share code, notes, and snippets.

@kdowswell
Created August 13, 2016 17:14
Show Gist options
  • Save kdowswell/6404f2fa70d3a39bcfe371f3f8e1c7c5 to your computer and use it in GitHub Desktop.
Save kdowswell/6404f2fa70d3a39bcfe371f3f8e1c7c5 to your computer and use it in GitHub Desktop.
/// <summary>
/// Decorator that applies save changes after a command is successfully run
/// </summary>
/// <typeparam name="TCommand"></typeparam>
public class TransactionalCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand> where TCommand : CommandBase
{
private readonly IDbContext _context;
private readonly ICommandHandler<TCommand> _decoratedCommandHandler;
public TransactionalCommandHandlerDecorator(IDbContext context, ICommandHandler<TCommand> decoratedCommandHandler)
{
_context = context;
_decoratedCommandHandler = decoratedCommandHandler;
}
public void Handle(TCommand command)
{
using (var transaction = _context.Database.BeginTransaction(IsolationLevel.ReadCommitted))
{
try
{
_decoratedCommandHandler.Handle(command);
_context.SaveChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment