问题
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