Skip to content

Commit

Permalink
Use resource filter instead of middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
danielmarbach committed May 30, 2023
1 parent ecb39ff commit d98024c
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 40 deletions.
@@ -0,0 +1,27 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using NServiceBus.TransactionalSession;

public sealed class MessageSessionFilter : IAsyncResourceFilter
{
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
context.HttpContext.Items.Add(nameof(MessageSessionFilter), null);

var session = context.HttpContext.RequestServices.GetRequiredService<ITransactionalSession>();
await session.Open(new SqlPersistenceOpenSessionOptions());

await next();

await session.Commit();
}
}

public sealed class RequiresTransactionalSession : ServiceFilterAttribute
{
public RequiresTransactionalSession() : base(typeof(MessageSessionFilter))
{
}
}

This file was deleted.

@@ -1,6 +1,7 @@
using Microsoft.Data.SqlClient;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Expand All @@ -10,7 +11,7 @@
using NServiceBus.TransactionalSession;

public class Program
{
{
// for SqlExpress use Data Source=.\SqlExpress;Initial Catalog=nservicebus;Integrated Security=True;Encrypt=false
const string ConnectionString = @"Server=localhost,1433;Initial Catalog=nservicebus;User Id=SA;Password=yourStrong(!)Password;Encrypt=false";

Expand Down Expand Up @@ -48,33 +49,56 @@ public static void Main()
#region txsession-ef-configuration
.ConfigureServices(c =>
{
// Configure Entity Framework to attach to the synchronized storage session
// Configure Entity Framework to attach to the synchronized storage session when required
c.AddScoped(b =>
{
var session = b.GetRequiredService<ISqlStorageSession>();
var context = new MyDataContext(new DbContextOptionsBuilder<MyDataContext>()
.UseSqlServer(session.Connection)
.Options);
var requiresSessionIntegration = true;
var contextAccessor = b.GetRequiredService<IHttpContextAccessor>();
if (contextAccessor.HttpContext != null && !contextAccessor.HttpContext.Items.TryGetValue(nameof(MessageSessionFilter), out _))
{
requiresSessionIntegration = false;
}
//Use the same underlying ADO.NET transaction
context.Database.UseTransaction(session.Transaction);
if (requiresSessionIntegration)
{
var session = b.GetRequiredService<ISqlStorageSession>();
var context = new MyDataContext(new DbContextOptionsBuilder<MyDataContext>()
.UseSqlServer(session.Connection)
.Options);
//Ensure context is flushed before the transaction is committed
session.OnSaveChanges((s) => context.SaveChangesAsync());
//Use the same underlying ADO.NET transaction
context.Database.UseTransaction(session.Transaction);
//Ensure context is flushed before the transaction is committed
session.OnSaveChanges((s) => context.SaveChangesAsync());
return context;
}
else
{
var context = new MyDataContext(new DbContextOptionsBuilder<MyDataContext>()
.UseSqlServer(ConnectionString)
.Options);
return context;
}
return context;
});
})
#endregion

.ConfigureWebHostDefaults(c =>
{
c.ConfigureServices(s => s.AddControllers());
c.Configure(app =>
c.ConfigureServices(s =>
{
s.AddControllers();
#region txsession-web-configuration
app.UseMiddleware<MessageSessionMiddleware>();
s.AddScoped<MessageSessionFilter>();
s.AddHttpContextAccessor();
#endregion
});
c.Configure(app =>
{
app.UseRouting();
app.UseEndpoints(r => r.MapControllers());
});
Expand All @@ -83,4 +107,4 @@ public static void Main()

host.Run();
}
}
}
@@ -1,6 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NServiceBus.TransactionalSession;

[ApiController]
Expand All @@ -18,6 +21,7 @@ public SendMessageController(ITransactionalSession messageSession, MyDataContext

#region txsession-controller
[HttpGet]
[RequiresTransactionalSession]
public async Task<string> Get()
{
var id = Guid.NewGuid().ToString();
Expand All @@ -31,4 +35,12 @@ await messageSession.SendLocal(message)
return $"Message with entity ID '{id}' sent to endpoint";
}
#endregion
}

#region txsession-controller-query
[HttpGet("/all")]
public async Task<List<MyEntity>> GetAll()
{
return await dataContext.MyEntities.ToListAsync();
}
#endregion
}

0 comments on commit d98024c

Please sign in to comment.