Created
August 13, 2016 17:11
-
-
Save kdowswell/1f757ea28fa030d09b02b6748777307f 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="TRequest"></typeparam> | |
/// <typeparam name="TResponse"></typeparam> | |
public class TransactionalHandler<TRequest, TResponse> | |
: IRequestHandler<TRequest, TResponse> | |
where TRequest : IRequest<TResponse> | |
{ | |
private readonly IAfaemsDbContext _context; | |
private readonly IRequestHandler<TRequest, TResponse> _inner; | |
public TransactionalHandler(IAfaemsDbContext context, IRequestHandler<TRequest, TResponse> inner) | |
{ | |
_context = context; | |
_inner = inner; | |
} | |
TResponse IRequestHandler<TRequest, TResponse>.Handle(TRequest message) | |
{ | |
using (var transaction = _context.Database.BeginTransaction(IsolationLevel.ReadCommitted)) | |
{ | |
try | |
{ | |
var result = _inner.Handle(message); | |
_context.SaveChanges(); | |
transaction.Commit(); | |
return result; | |
} | |
catch (Exception) | |
{ | |
transaction.Rollback(); | |
throw; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment