-
Notifications
You must be signed in to change notification settings - Fork 6
Implementation
We suggest that you ONLY use DomainEvents with actual domain entities. In our team's typical architecture, domain entities are always retrieved by some sort of domain-level “service”. Take an “IAccountFetcher” like this for example:
public interface IAccountFetcher {
Account FetchById(long id);
}Assuming we always fetch accounts using this fetcher service, then implementing the DomainEvents infrastructure is fairly simple. You would inject the initializer in your service and initialize any entities that it returns. Like this:
public class InitializedAccountFetcher : IAccountFetcher {
IDomainEventInitializer _initializer;
IRepository _repository;
public InitializedAccountFetcher(IDomainEventInitializer initializer, IRepository repository) {
_initializer = initializer;
_repository = repository;
}
public Account FetchById(long id) {
var account = _repository.Get(id);
return _initializer.Initialize(account);
}
}You also need to be sure to register the initializer and dispatcher in your IOC container. If you're using structureMap, here's a suggested configuration (using a registry):
public class StandardDomainEventsConfiguration : Registry
{
public StandardDomainEventsConfiguration() {
For<IDomainEventInitializer>().Use<DomainEventInitializer>();
For<IDomainEventDispatcher>().Use<StructureMapDomainEventDispatcher>();
}
}All that's left is to register your handlers. If you're planning on using the “StructureMapDomainEventDispatcher”, you can do something like this in your app's bootstrapper (including adding the above registry):
var container = new Container();
container.Configure(x => {
x.AddRegistry<StandardDomainEventsConfiguration>();
x.For<IDomainEventHandler<TheNameChanged>>().Use<LogThatNameChanged>();
});In summary, to implement DomainEvents, you must:
- Register an implementation of IDomainEventInitializer in your IOC container.
- Register an implementation of IDomainEventDispatcher in your IOC container.
- Register all implementations of IDomainEventHandler<> in your IOC container.
- Always “initialize” your domain entities using an injected IDomainEventInitializer.
- Add just one DomainEvent event field to each domain entity with a name like “NotifyObservers”.
- Start raising DomainEvents in your behavior-rich domain entities.