Integrating DI container within domain layer. Doma

2019-09-01 05:40发布

问题:

Following the article: http://www.udidahan.com/2009/06/14/domain-events-salvation/ we can see that DomainEvents implemantation uses DI container

public static IContainer Container { get; set; }

and then

if(Container != null) {
    foreach(var handler in Container.ResolveAll<Handles<T>>()) handler.Handle(args);
}

Should I integrate DI container inside the same assembly I store domain objects or can I externalize/abstract away the Container.ResolveAll<Handles<T>>()? (In my previous experiences I put all DI-related stuff inside global.asax.cs).

Technically I'm familiar only with Ninject DI container but probably will understand the concept so your advices/illustrations are appreciated.

Thanks!

回答1:

No it is not necessary. I'd make DomainEvents and its methods non-static and use the container to create it. A decent container will create and initialize the Handles and their dependencies and allow you to call the event handlers without any reference to the container.

The only catch is the registration of the event handlers. For that I use Bootstrapper to call instances of IUnityRegistration and configure UNITY. I started to use CommonServiceLocator to reduce dependencies. And even more recently, I switched to MEF to get rid of the registration classes all together.