在 Ninject 2 中,如何让两个具有不同设置的内核共享绑定?
我的应用程序有一个 Ninject 2 内核,其中包含所有绑定。应用程序的一个部分需要在内核上具有与应用程序的其余部分不同的设置,但需要相同的绑定(该部分用于 NHibernate,并且需要 InjectNonPublic = true
和 InjectAttribute< /代码> 设置)。如何制作一个与当前内核共享绑定但具有不同设置的内核?
我相信在其他 IOC 容器中,这可以通过“嵌套容器”来实现,但是我在 Ninject 中没有看到任何对嵌套容器的支持?
I have a single Ninject 2 Kernel for my application which contains all bindings. One section of the application needs to have different settings on the Kernel than the rest of the application, but needs the same bindings (that portion is for NHibernate and needs InjectNonPublic = true
and the InjectAttribute
set). How can a make a Kernel that shares bindings with the current kernel but has different settings?
I believe that in other IOC containers this is would be achieved with a "nested container", however I don't see any support for nested containers in Ninject?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过 Ninject.Extensions.ChildKernel 扩展?
Have you tried the Ninject.Extensions.ChildKernel extension?
我最终解决了我的问题。正如我所说,我真正所做的是尝试自定义注入以供 NHibernate 使用。为了解决这个问题,我最终使用 Ninject 的内部 IOC 来替换其行为的某些策略。
在内部,Ninject 使用 ISelector 的实例来确定它应该考虑调用哪些构造函数。我通过装饰标准选择器重新实现了此类(我无法对标准进行子类化并重写,因为没有一个方法是虚拟的)。然后我可以有条件地更改
SelectConstructorsForInjection()
方法的行为。上面的内容本质上是为水合类型执行
InjectNonPublic = true
。但我仍然需要为这些类型设置InjectAttribute
。我通过替换 HydratingConstructorScorer 来实现这一点,如下所示:然后,我通过创建一个特殊的内核来合并这些新策略,如下所示:
I eventually solved my problem. As I said, what I was really doing was trying to customize injection for use by NHibernate. In order to solve this I ended up using Ninject's internal IOC to replace certain strategies for its behavior.
Internally, Ninject uses an instance of ISelector to determine which constructors it should consider invoking. I reimplemented this class by decorating the standard Selector (I couldn't subclass the standard and override because none of the methods are virtual). I could then conditionally change the
SelectConstructorsForInjection()
method's behavior.The above took care of essentially doing
InjectNonPublic = true
for the hydrated types. But I still needed to do the equivalent of setting theInjectAttribute
for those types. This I did by replacing theHydratingConstructorScorer
like so:I then incorporated these new strategies by creating a special Kernel like so: