c# - SimpleInjector 为 RegisterManyForOpenGeneric 重复注册,以实现具有多个接口(interface)的实现

标签 c# inversion-of-control ioc-container simple-injector

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

在我的应用程序中,外部输入引发一个事件,然后将该事件分派(dispatch)到实现 IEventHandler<> 的所有类。传入事件类型:

// 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<>类会自动连接,并且通过上述代码发布的所有事件都会发送到处理程序(对于上述场景,我有 single 接口(interface) IEventHandler<AdminActedOnTopic> )。

但是,如果我在同一实现类中注册多个事件处理程序接口(interface):

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 版本开始修复。

关于c# - SimpleInjector 为 RegisterManyForOpenGeneric 重复注册,以实现具有多个接口(interface)的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28507879/

相关文章:

c# - 在循环中打开和关闭连接的正确方法

c# - `Where` 中新对象的 Linq 查询性能

c# - 在 Windows 7 中分析文件的碎片

c# - Unity(依赖注入(inject)): How to pass in a parameter to the constructor in RegisterType

c# - 使用 IOC 容器的策略设计模式 - 专门用于 Ninject

c# - 如何在.net core中使用 "System.Net.ServicePointManager"?

python - 设计模式名称 : get class from class level

asp.net - 如何在 ASP.NET Web 窗体中使用依赖注入(inject)

php - Laravel - 我的每个服务容器/自定义类都需要一个服务提供商吗?

c# - 使用 CommonServiceLocator 将依赖项注入(inject)基类是一种好习惯吗?