-
Notifications
You must be signed in to change notification settings - Fork 4
refactor: refactor DispatchDomainEventsAsync #94
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
@@ -173,6 +173,12 @@ private async Task ExtraAndPublishDomainEventsAsync() | |||
var entities = Context.ExtractDomainEventSources(); | |||
var domainEvents = entities.SelectMany(x => x.DomainEvents!.OfType<DomainEvent>()).ToList(); | |||
entities.ForEach(x => x.ClearDomainEvents()); | |||
|
|||
if (domainEvents is null || domainEvents.Any() == false) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个在 ExtractDomainEventSources
里已经检查过了。
public static List<IDomainEventSource> ExtractDomainEventSources(this DbContext ctx)
{
var domainEntities = ctx.ChangeTracker
.Entries<IDomainEventSource>()
.Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any())
.Select(x => x.Entity)
.ToList();
return domainEntities;
}
} | ||
else | ||
{ | ||
await mediator.Publish(domainEvent); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
判断之后两个分支都执行的同样的语句,那为什么要判断呢?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
可以直接让 IDomainEvent 继承 INotification。
{ | ||
try |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个 Try...Catch 目的是当出现异常时保证其他领域事件被发布,这样后续如果要回滚可以直接全部回滚。不 catch 的话领域事件发到一半就挂了,剩下的不会被发布,而且不知道哪些发了哪些没发,导致一致性出现问题。设计上领域事件是顺序无关的,编程时不应该考虑领域事件的添加顺序。
这里把多的异常吃了确实是个问题,等下我加个 CombinedException 汇总一下异常再统一抛出来。
@@ -15,22 +15,21 @@ public static class DispatchDomainEventExtensions | |||
/// <param name="events">要发布的领域事件。</param> | |||
public static async Task DispatchDomainEventsAsync(this IMediator mediator, IEnumerable<IDomainEvent> events) | |||
{ | |||
Exception? e = null; | |||
foreach (var domainEvent in events) | |||
foreach (var domainEvent in events ?? Enumerable.Empty<IDomainEvent>()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
本来开了 nullable reference 是不需要判空的,实在要判的话也应该直接返回而不是新建一个空数组。
看起来是在没开 nullable reference 的项目里试图直接注入 IMediator 发领域事件,然后领域事件类直接继承的 IDomainEvent 而不是 DomainEvent 出现的问题。 |
No description provided.