Skip to content

Instantly share code, notes, and snippets.

@merken
Last active September 28, 2018 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merken/dd9bc5f116799d6399706ee290661c1e to your computer and use it in GitHub Desktop.
Save merken/dd9bc5f116799d6399706ee290661c1e to your computer and use it in GitHub Desktop.
using System;
using System.Data;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
namespace txn
{
public class UnitOfWorkFilter : IAsyncActionFilter
{
private readonly IDbTransaction transaction;
public UnitOfWorkFilter(IDbTransaction transaction)
{
this.transaction = transaction;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var connection = transaction.Connection;
if (connection.State != ConnectionState.Open)
throw new NotSupportedException("The provided connection was not open!");
var executedContext = await next.Invoke();
if (executedContext.Exception == null)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment