Skip to content

Instantly share code, notes, and snippets.

@dataneek
Last active October 1, 2017 12:51
Show Gist options
  • Save dataneek/80ce816e03e6e70c1e6b2a1e1f488ee1 to your computer and use it in GitHub Desktop.
Save dataneek/80ce816e03e6e70c1e6b2a1e1f488ee1 to your computer and use it in GitHub Desktop.
Single Connection per Page Request in Razor Pages 2.0
namespace WebApp.Models
{
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
public class DbContextTransactionFilter : IAsyncPageFilter
{
async Task IAsyncPageFilter.OnPageHandlerExecutionAsync(
PageHandlerExecutingContext context,
PageHandlerExecutionDelegate next)
{
var db =
context.HttpContext.RequestServices.GetService(typeof(AppDbContext)) as AppDbContext;
try
{
await db.BeginTransactionAsync();
await next();
await db.CommitTransactionAsync();
}
catch (Exception)
{
db.RollbackTransaction();
throw;
}
}
Task IAsyncPageFilter.OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
{
return Task.CompletedTask;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment