1

我有点困惑,我有一个关于 domainevents 的片段,其中 `

public class StructureMapDomainEventHandlerFactory : IDomainEventHandlerFactory
{
    public IEnumerable<IDomainEventHandler<T>> GetDomainEventHandlersFor<T>
                                           (T domainEvent) where T : IDomainEvent
        return ObjectFactory.GetAllInstances<IDomainEventHandler<T>>();
}

其中利用了 StructureMap。我刚刚开始使用 Autofac 进行 DI,这应该如何在 Autofac 中实现。因为没有静态类的概念。

一般来说,这种方法是否正确?在 Factory 类中使​​用 DI 有什么意义,直接在其他地方引用它不是很好吗?

4

1 回答 1

2

这个特定的示例实际上是为您提供 OOB。只需依赖IEnumerable<IDomainEventHandler<>>,Autofac 就会为您提供集合:

public class ClientClass
{
     public ClientClass(IEnumerable<IDomainEventHandler<OfSomeType>> eventHandlers)
     {
     }
}

更新:这是一个工厂类的示例,其中可能包含一些关于从容器解析服务的逻辑:

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>>>();
    }
}

也就是说,我鼓励您探索在 Autofac 中使用强类型元数据的可能性。通过使用元数据“标记”服务,工厂类可以仅通过检查元数据来执行广泛的逻辑,从而尽可能少地依赖于实际使用的框架。

更新 2:感谢@Nicholas,这是使用 Autofac 处理域事件的绝佳示例方法。可以在此处找到将事件传播到处理程序的类。

于 2011-07-28T13:12:33.410 回答