Is it possible to implement MediatR in the Aggregates (Domain Layer) without dependency injection (DDD)?

给你一囗甜甜゛ 提交于 2020-01-02 10:22:19

问题


To prevent reinventing the wheel, I'd like to use MediatR in the Aggregates to publish domain events. (Un)Fortunately(?) MediatR works as a dependency that is injected into the classes, and not something that I can call statically. Therefore I'd end up creating a direct dependency on the library via the constructor.

I don't remember where I read it (and if I read it right), that I should avoid non-business dependencies in the constructors of the Aggregates.

Therefore, I shouldn't do something like this:

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

That made me think deeply whether it was possible or recommended (Or not recommended) to use MediatR in the Aggregates...

Is there a way for me to use MediatR statically or should I implement my own Event Dispatcher?

P.S: Also, feel free to correct me if my understanding of the Aggregates dependencies are wrong.

P.S x2: I've searched Google and SO and can't find an answer to this. https://stackoverflow.com/search?q=mediatr+domain+events How to decouple MediatR from my business layer DDD: Referencing MediatR interface from the domain project


回答1:


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



来源:https://stackoverflow.com/questions/54246127/is-it-possible-to-implement-mediatr-in-the-aggregates-domain-layer-without-dep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!