Last active
October 1, 2017 12:51
-
-
Save dataneek/80ce816e03e6e70c1e6b2a1e1f488ee1 to your computer and use it in GitHub Desktop.
Single Connection per Page Request in Razor Pages 2.0
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
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