forked from amantinband/clean-architecture
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventualConsistencyMiddleware.cs
41 lines (34 loc) · 1.17 KB
/
EventualConsistencyMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using CleanArchitecture.Domain.Common;
using MediatR;
using Microsoft.AspNetCore.Http;
namespace CleanArchitecture.Infrastructure.Common.Middleware;
public class EventualConsistencyMiddleware(RequestDelegate _next)
{
public const string DomainEventsKey = "DomainEventsKey";
public async Task InvokeAsync(HttpContext context, IPublisher publisher, AppDbContext dbContext)
{
var transaction = await dbContext.Database.BeginTransactionAsync();
context.Response.OnCompleted(async () =>
{
try
{
if (context.Items.TryGetValue(DomainEventsKey, out var value) && value is Queue<IDomainEvent> domainEvents)
{
while (domainEvents.TryDequeue(out var nextEvent))
{
await publisher.Publish(nextEvent);
}
}
await transaction.CommitAsync();
}
catch (Exception)
{
}
finally
{
await transaction.DisposeAsync();
}
});
await _next(context);
}
}