Skip to content

Instantly share code, notes, and snippets.

@kdowswell
Created August 13, 2016 17:11
Show Gist options
  • Save kdowswell/1f757ea28fa030d09b02b6748777307f to your computer and use it in GitHub Desktop.
Save kdowswell/1f757ea28fa030d09b02b6748777307f to your computer and use it in GitHub Desktop.
/// <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