Created
August 13, 2016 17:14
-
-
Save kdowswell/6404f2fa70d3a39bcfe371f3f8e1c7c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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