2
2
using KSFramework . Utilities ;
3
3
using Microsoft . EntityFrameworkCore ;
4
4
using Project . Infrastructure . Outbox ;
5
+ using Microsoft . Extensions . DependencyInjection ;
6
+ using Project . Infrastructure . Services ;
7
+ using System . Linq ;
5
8
6
9
namespace Project . Infrastructure . Data ;
7
10
8
11
public class ApplicationDbContext : DbContext
9
12
{
10
- public ApplicationDbContext ( DbContextOptions < ApplicationDbContext > options )
11
- : base ( options )
13
+ private readonly IDomainEventDispatcher _dispatcher ;
14
+ private readonly IServiceProvider _serviceProvider ;
15
+
16
+ public ApplicationDbContext (
17
+ DbContextOptions < ApplicationDbContext > options ,
18
+ IServiceProvider serviceProvider )
19
+ : base ( options )
12
20
{
21
+ _serviceProvider = serviceProvider ;
22
+ _dispatcher = _serviceProvider . GetRequiredService < IDomainEventDispatcher > ( ) ;
13
23
}
14
24
15
25
public DbSet < OutboxMessage > OutboxMessages { get ; set ; }
@@ -48,4 +58,26 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
48
58
49
59
#endregion
50
60
}
61
+
62
+ public override async Task < int > SaveChangesAsync ( CancellationToken cancellationToken = default )
63
+ {
64
+ var domainEvents = ChangeTracker . Entries < BaseEntity > ( )
65
+ . SelectMany ( x => x . Entity . DomainEvents )
66
+ . ToList ( ) ;
67
+
68
+ var result = await base . SaveChangesAsync ( cancellationToken ) ;
69
+
70
+ if ( domainEvents . Any ( ) )
71
+ {
72
+ await _dispatcher . DispatchEventsAsync ( domainEvents , cancellationToken ) ;
73
+
74
+ // Clear domain events after dispatching
75
+ foreach ( var entry in ChangeTracker . Entries < BaseEntity > ( ) )
76
+ {
77
+ entry . Entity . ClearDomainEvents ( ) ;
78
+ }
79
+ }
80
+
81
+ return result ;
82
+ }
51
83
}
0 commit comments