Skip to content

Commit

Permalink
Merge pull request #86 from Etherna/improve/BHM-124-reorder-db-ops
Browse files Browse the repository at this point in the history
Refactor event dispatching in persistence layer
  • Loading branch information
tmm360 authored Dec 2, 2024
2 parents 9681ff6 + f5bb88e commit f9c389f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
9 changes: 6 additions & 3 deletions src/Beehive.Persistence/BeehiveDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,17 @@ where t.GetInterfaces().Contains(typeof(IModelMapsCollector))
// Public methods.
public override async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{
var changedEntityModels = ChangedModelsList.OfType<EntityModelBase>().ToArray();

// Save changes.
await base.SaveChangesAsync(cancellationToken);

// Dispatch events.
foreach (var model in ChangedModelsList.OfType<EntityModelBase>())
foreach (var model in changedEntityModels)
{
await EventDispatcher.DispatchAsync(model.Events);
model.ClearEvents();
}

await base.SaveChangesAsync(cancellationToken);
}

// Protected methods.
Expand Down
18 changes: 9 additions & 9 deletions src/Beehive.Persistence/Repositories/DomainRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class DomainRepository<TModel, TKey> :
Repository<TModel, TKey>
where TModel : EntityModelBase<TKey>
{
// Constructors and initialization.
// Constructors.
public DomainRepository(string name)
: base(name)
{ }
Expand Down Expand Up @@ -86,20 +86,20 @@ public override async Task DeleteAsync(TModel model, CancellationToken cancellat
{
ArgumentNullException.ThrowIfNull(model, nameof(model));

// Dispatch custom events.
if (EventDispatcher != null)
{
await EventDispatcher.DispatchAsync(model.Events);
model.ClearEvents();
}

// Delete entity.
await base.DeleteAsync(model, cancellationToken);

// Dispatch deleted event.
// Dispatch events.
if (EventDispatcher != null)
{
//deleted event
await EventDispatcher.DispatchAsync(
new EntityDeletedEvent<TModel>(model));

//custom events
await EventDispatcher.DispatchAsync(model.Events);
model.ClearEvents();
}
}
}
}

0 comments on commit f9c389f

Please sign in to comment.