SimpleInjector 为具有多个接口的实现重复注册 RegisterManyForOpenGeneric

SimpleInjector duplicate registrations for RegisterManyForOpenGeneric for implementations with more than one interface

我有一个关于 IEventHandler<> 自动注册到 RegisterManyForOpenGeneric 的问题,这会导致重复注册(我确定我做错了)。

在我的应用程序中,外部输入引发了一个事件,然后将其分派给所有实现传入事件类型 IEventHandler<> 的 classes:

// during bootstrap, the below code is called
resolver.RegisterManyForOpenGeneric(typeof(IEventHandler<>), AppDomain.CurrentDomain.GetAssemblies());

// when the app is running, an external event is published below:
public void PublishEvent(object evnt)
{
    var handlerType = (typeof(IEventHandler<>)).MakeGenericType(evnt.getType());
    var handlers = resolver.GetAllInstances(handlerType).ToList();

    foreach(var handler in handlers)
    {
        /* do some reflection to get method */
        method.Invoke(handler, new[] { evnt } });
    }
}

// the below is an event handlers that get automatically wired up OK
class TopicVoteStatisticsProjection : IEventHandler<AdminActedOnTopic>
{
    public void Handle(AdminActedOnTopic evnt)
    {
        // for every event, this gets called once and all is good
    }    
}

以上所有 IEventHandler<> classes 都自动连接,并且通过上述代码发布的所有事件都发送到处理程序 OK(对于上面的场景,我有 接口IEventHandler<AdminActedOnTopic>).

但是如果我在同一实现中注册了多个事件处理程序接口class:

class TopicVoteStatisticsProjection : IEventHandler<UserVotedOnTopic>, IEventHandler<AdminActedOnTopic>
{
    public void Handle(UserVotedOnTopic evnt)
    {
    }

    public void Handle(AdminActedOnTopic evnt)
    {
        // for every event, this gets called twice!!
    }
}

然后发生的是 IEventHandler 的同一个处理程序被返回两次:

handlers = resolver.GetAllInstances(typeof(IEventHandler<AdminActedOnTopic>)).ToList();

/* above query returns the following instances: 
Projections.TopicVoteStatistics.TopicVoteStatisticsProjection
Projections.TopicVoteStatistics.TopicVoteStatisticsProjection
*/

这很糟糕,因为它在我的计算中加倍了!在这种情况下,这两个事件是相关的,理想情况下我希望将它们放在同一个处理程序实现中。

我的问题是 - 如何自动注册处理程序,其中一些实现多个 IEventHandler<> 接口,而不重复注册?

我认为您看到的行为是 2.7 版中引入的错误。这里有详细描述:https://simpleinjector.codeplex.com/workitem/20996

应该从2.7.2版本开始修复。