首页 > 解决方案 > 是否可以在没有依赖注入 (DDD) 的聚合(域层)中实现 MediatR?

问题描述

为了防止重新发明轮子,我想在聚合中使用 MediatR 来发布域事件。(Un)幸运的是(?)MediatR 作为注入到类中的依赖项工作,而不是我可以静态调用的东西。因此,我最终会通过构造函数创建对库的直接依赖。

我不记得我在哪里读过它(如果我没看错的话),我应该避免聚合的构造函数中的非业务依赖。

因此,我不应该这样做:

public class MyAggregate
{
    private readonly IMediator _mediator;
    public MyAggregate(IMediator mediator)
    {
        _mediator = mediator;
    }
}

这让我深入思考是否可以或推荐(或不推荐)在聚合中使用 MediatR...

有没有办法让我静态使用 MediatR 或者我应该实现自己的事件调度程序?

PS:另外,如果我对聚合依赖项的理解有误,请随时纠正我。

PS x2:我搜索了 Google 和 SO,但找不到答案。 https://stackoverflow.com/search?q=mediatr+domain+events 如何将 MediatR 与我的业务层 DDD 解耦:从域项目中引用 MediatR 接口

标签: domain-driven-designaggregatemediatrdomain-events

解决方案


I should avoid non-business dependencies in the constructors of the Aggregates.

Not only in constructors; your business layer should not have dependencies to non-business in any form; even static.

What I do is just return the domain event from the aggregate to the application layer and then publish the domain event.

Please read these couple of post to better understand what I mean:

Don't publish Domain Events, return them! DDD-Application-Services-Explained


推荐阅读