54 lines
1.7 KiB
C#
54 lines
1.7 KiB
C#
using GozareshgirProgramManager.Domain._Common;
|
|
using GozareshgirProgramManager.Infrastructure.Persistence.Context;
|
|
using MediatR;
|
|
using Microsoft.Identity.Client;
|
|
using GozareshgirProgramManager.Application._Common.Models;
|
|
|
|
namespace GozareshgirProgramManager.Infrastructure.Persistence;
|
|
|
|
public class UnitOfWork : IUnitOfWork
|
|
{
|
|
private readonly ProgramManagerDbContext _context;
|
|
private readonly IPublisher _publisher;
|
|
|
|
public UnitOfWork(ProgramManagerDbContext context, IPublisher publisher)
|
|
{
|
|
_context = context;
|
|
_publisher = publisher;
|
|
}
|
|
|
|
public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
// Publish Domain Events before saving
|
|
await PublishDomainEvents(cancellationToken);
|
|
|
|
return await _context.SaveChangesAsync(cancellationToken);
|
|
}
|
|
|
|
private async Task PublishDomainEvents(CancellationToken cancellationToken)
|
|
{
|
|
var domainEntities = _context.ChangeTracker
|
|
.Entries<EntityBase<Guid>>()
|
|
.Where(x => x.Entity.DomainEvents.Any())
|
|
.ToList();
|
|
|
|
var domainEvents = domainEntities
|
|
.SelectMany(x => x.Entity.DomainEvents)
|
|
.ToList();
|
|
|
|
domainEntities.ForEach(entity => entity.Entity.ClearDomainEvents());
|
|
|
|
foreach (var domainEvent in domainEvents)
|
|
{
|
|
var notificationType = typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType());
|
|
var notification = Activator.CreateInstance(notificationType, domainEvent);
|
|
|
|
if (notification != null)
|
|
{
|
|
await _publisher.Publish(notification, cancellationToken);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|