如何使用Ninject装饰绑定到多种具体类型的接口 [英] How to decorate interfaces bound to more than one concrete type with Ninject

查看:85
本文介绍了如何使用Ninject装饰绑定到多种具体类型的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一条消息总线,可通过Ninject实例化消息处理程序.我想用诸如日志记录,事务管理等横切关注点来装饰我的处理程序.

So, I have a message bus that instantiates message handlers through Ninject. I'd like to decorate my handlers with cross cutting concerns such as logging, transaction management, etc.

我这样设置绑定:

kernel.Bind<IMessageHandler<int>>().To<IntHandlerOne>()
    .WhenInjectedInto(typeof(HandlerDecorator<>));
kernel.Bind(typeof(IMessageHandler<>)).To(typeof(HandlerDecorator<>));

每当我有一个特定消息类型的处理程序时,哪个工作起来都很出色.但是,当我定义了多个处理程序时:

Which works fantastically whenever I have a single handler of a specific message type. However, when I have more than one handler defined:

kernel.Bind<IMessageHandler<int>>().To<IntHandlerOne>()
    .WhenInjectedInto(typeof(HandlerDecorator<>));
kernel.Bind<IMessageHandler<int>>().To<IntHandlerTwo>()
    .WhenInjectedInto(typeof(HandlerDecorator<>));
kernel.Bind(typeof(IMessageHandler<>)).To(typeof(HandlerDecorator<>));

Ninject将找到装饰器并将其注入到消息总线,然后尝试将两个处理程序都注入到装饰器构造器中而失败.

Ninject will find and inject the decorator to the message bus, and then attempt unsuccessfully to inject both handlers into the decorator constructor.

public HandlerDecorator(IMessageHandler<T> handler)

您可能在想,为什么我不只是修改装饰器以接受处理程序列表?我曾考虑过这一点,但这违背了处理程序的目的.我希望能够轻松地将多个装饰器透明地链接在一起. IMessageHandler<T>的每个实例都应该获得一个全新的处理程序链.

You may be thinking, why don't I just modify my decorator to accept the list of handlers? I thought about this, but that defeats the purpose of the handler. I want to be able to easily chain multiple decorators together transparently. Each instance of IMessageHandler<T> should get an entirely new chain of handlers.

我已经在GitHub上发布了示例测试库,该库应该可以说明我在说什么在这里.

I've published an example test library on GitHub that should illustrate what I'm talking about here.

Ninject有什么办法做到这一点吗?

Is there any way to do this in Ninject?

推荐答案

使用

kernel.Bind<IMessageHandler<int>>().To<IntHandlerOne>().WhenParentNamed("One");
kernel.Bind<IMessageHandler<int>>().To<IntHandlerTwo>().WhenParentNamed("Two");
kernel.Bind(typeof(IMessageHandler<>)).To(typeof(HandlerDecorator<>)).Named("One");
kernel.Bind(typeof(IMessageHandler<>)).To(typeof(HandlerDecorator<>)).Named("Two");

还请注意,大多数总线框架都有某种方式可以对消息处理程序进行修饰.可以先看看那里.

Also be aware that most of the Bus Frameworks have some way to do decorations for message handlers. May have a look there first.

这篇关于如何使用Ninject装饰绑定到多种具体类型的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆