简单的注射器条件注射
假设我有两个控制器:ControllerA和ControllerB。 这两个控制器都接受参数IFooInterface。 现在我有2个IFooInterface,FooA和FooB的实现。 我想在ControllerA中注入FooA,在ControllerB中注入FooB。 这很容易在Ninject中实现,但由于性能更好,我正在转向Simple Injector。 那么我怎样才能在Simple Injector中做到这一点? 请注意,ControllerA和ControllerB驻留在不同的程序集中并动态加载。
谢谢
SimpleInjector文档调用此基于上下文的注入 。 从版本3开始,您将使用RegisterConditional
。 从版本2.8开始,此function未在SimpleInjector中实现,但是文档包含实现此function的工作代码示例,作为Container
类的扩展。
使用这些扩展方法,你会做这样的事情:
Type fooAType = Assembly.LoadFrom(@"pathtofooA.dll").GetType("FooA"); Type fooBType = Assembly.LoadFrom(@"pathtofooB.dll").GetType("FooB"); container.RegisterWithContext(context => { if (context.ImplementationType.Name == "ControllerA") { return container.GetInstance(fooAType); } else if (context.ImplementationType.Name == "ControllerB") { return container.GetInstance(fooBType) } else { return null; } });
由于版本3 Simple Injector具有RegisterConditional方法
上述就是C#学习教程:简单的注射器条件注射分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
container.RegisterConditional(c => c.Consumer.ImplementationType == typeof(ControllerA)); container.RegisterConditional(c => c.Consumer.ImplementationType == typeof(ControllerB)); container.RegisterConditional(c => !c.Handled);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1038775.html