using Autofac in Factory method
I am bit confused I have a snippet on domain开发者_JAVA技巧events where `
public class StructureMapDomainEventHandlerFactory : IDomainEventHandlerFactory
{
public IEnumerable<IDomainEventHandler<T>> GetDomainEventHandlersFor<T>
(T domainEvent) where T : IDomainEvent
return ObjectFactory.GetAllInstances<IDomainEventHandler<T>>();
}
where StructureMap is exploited. I just embarked on DI using Autofac how this supposed to be implemented in Autofac. Since there is no notion of Static Class.
In general is this approach correct ? what is the point of using DI within the Factory class would not be nice to refer it directly somewhere else ?
This particular example is actually provided for you OOB. Just take a dependency on IEnumerable<IDomainEventHandler<>>
and Autofac will serve the collection to you:
public class ClientClass
{
public ClientClass(IEnumerable<IDomainEventHandler<OfSomeType>> eventHandlers)
{
}
}
Update: here's an example of a factory class that could include some logic around resolving services from a container:
public class AutofacDomainEventHandlerFactory : IDomainEventHandlerFactory
{
private readonly IComponentContext _context;
public AutofacDomainEventHandlerFactory(IComponentContext context)
{
_context = context;
}
public IEnumerable<IDomainEventHandler<T>> GetDomainEventHandlersFor<T>
(T domainEvent) where T : IDomainEvent
{
return _context.Resolve<IEnumerable<IDomainEventHandler<T>>>();
}
}
That said, I encourage you to explore the possibilities of using strongly-typed metadata in Autofac. By "tagging" services with metadata, factory classes can do extensive logic only by examining the metadata and thus have as little as possible dependency on the actual framework used.
Update 2: thanks to @Nicholas, here's an excellent sample approach to domain events using Autofac. The class that propagate events to handlers can be found here.
精彩评论