问题描述
假设我有两个控制器:ControllerA和ControllerB。这两个控制器都接受IFooInterface作为参数。现在,我有2个IFooInterface,FooA和FooB的实现。我想在ControllerA中注入FooA,在ControllerB中注入FooB。这在Ninject中很容易实现,但是由于性能更好,我将转向Simple Injector。那么如何在Simple Injector中做到这一点呢?请注意,ControllerA和ControllerB驻留在不同的程序集中,并且是动态加载的。
Lets say I have two Controllers: ControllerA and ControllerB. Both of those controllers accept as parameter IFooInterface. Now I have 2 implementation of IFooInterface, FooA and FooB. I want to inject FooA in ControllerA and FooB in ControllerB. This was easily achieved in Ninject, but I'm moving to Simple Injector due to better performance. So how can I do this in Simple Injector? Please note that ControllerA and ControllerB resides in different assemblies and are loaded dynamically.
谢谢
推荐答案
SimpleInjector文档将其称为。从版本3开始,您将使用 RegisterConditional
。从2.8版开始,此功能尚未在SimpleInjector中实现,但是文档包含作为 Container
类的扩展。
The SimpleInjector documentation calls this context-based injection. As of version 3, you would use RegisterConditional
. As of version 2.8, this feature isn't implemented in SimpleInjector, however the documentation contains a working code sample implementing this feature as extensions to the Container
class.
使用这些扩展方法像这样的东西:
Using those extensions methods you would do something like this:
Type fooAType = Assembly.LoadFrom(@"path\to\fooA.dll").GetType("FooA");
Type fooBType = Assembly.LoadFrom(@"path\to\fooB.dll").GetType("FooB");
container.RegisterWithContext<IFooInterface>(context => {
if (context.ImplementationType.Name == "ControllerA")
{
return container.GetInstance(fooAType);
}
else if (context.ImplementationType.Name == "ControllerB")
{
return container.GetInstance(fooBType)
}
else
{
return null;
}
});
这篇关于简单注射器条件注射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!