AutofacEvents
AutofacEvents copied to clipboard
Publish Events from Entity; Handle from Aggregate
Does this solution support having a child Entity in an Aggregate raise an event, with the handler being on the parent/aggregate root?
That should work depending on two things:
- That the Aggregate was created by Autofac. If you do the following, Autofac doesn't know about agg so it won't publish to agg:
var agg = new SomeAggregate();
agg.Child.Send(new SomeEvent("Hi"));
- Scope - If SomeAggregate is registered as Instance Per Dependency then Autofac would create a new instance of SomeAggregate and publish the event there. So it wouldn't be received by specific
agg
instance in the above example. But if SomeAggregate were registered as Single Instance or Instance Per Lifetime Scope and the Child published the event using the same ILifetimeScope that created SomeAggregate, then yes,agg
should get the event.
The trick is that Aggregates/Entities aren't created by Autofac, but typically are either instantiated directly (if brand new) or retrieved from a Repository. What I've been working on is a way to statically access domain events from within the entities/aggregates, so that I wouldn't have to pass in an instance of Autofac or some IDomainEventService to make it work.
I think one of my colleagues has something working now (like literally in the last hour) so hopefully I'm all set. I do have a couple of domain event samples in my GitHub repos that you may be interested in if this is something you're actively working on. This is one: https://github.com/ardalis/DDD-NoDuplicates and this is another: https://github.com/ardalis/AggregateEvents