如何使用Simple Injector返回基于其父对象的实例? [英] How to return an instance based on its parent using Simple Injector?
问题描述
我们一直在使用温莎城堡作为我们的DI集装箱,但我们正在寻找替代方案。现在,我进入了简单注入器,到目前为止,它的简单性给我留下了深刻的印象,但是现在我遇到的一种情况是,当我们对某些组件使用后期绑定实例化时。
We have been using Windsor Castle as our DI Container but we are looking around for alternatives. Now I got to the Simple Injector and so far I have been impressed by its simplicity but one scenario I am stuck at right now is when we are using late bound instantiation for some of our components.
我的第一个问题是,可能吗?
My first question is, is it even possible?
使用温莎(Windsor)就是这样;
With Windsor it is done like this;
Container.Register(Component.For<ILogger>()
.UsingFactoryMethod(
(kernel, componentModel, context) => new Logger(
context.Handler.ComponentModel.Implementation.Name));
是否可以使用Simple Injector进行相同的操作?
Is there a way to do the same with Simple Injector?
推荐答案
使用Simple Injector,您将只需:
With Simple Injector, you will just have to either:
- 注册一个使用
Register< Func< A,B,C>>(((a,b)=> {...}})
$ b明确地进行Func委托$ b - 创建一个接口,例如
ILoggerFactory
,创建一个实现并注册它们。
- Register a Func delegate explicitly using
Register<Func<A, B, C>>((a, b) => { ... })
- Create an interface such as
ILoggerFactory
, creste an implementation and register them.
更新
再次阅读问题并查找Castle的 UsingFactoryMethod $的定义
我得出的结论是我误解了您的问题。或根据其父类型创建实例:基于上下文的注入。
After reading your question again and looking up the definition of Castle's UsingFactoryMethod
I came to the conclusion that I misinterpreted your question. What you are looking for is creating an instance based on its parent type: Context Based Injection.
您可以通过实现基于上下文的注入扩展方法,在Simple Injector文档Wiki上作为示例给出。
You can achieve this by implementing the Context Based Injection Extension method that is given as example on the Simple Injector's documentation wiki.
将此扩展方法添加到项目中时您可以执行以下等效注册:
When you add this extension method to your project you can do the equivalent registration as follows:
container.RegisterWithContext<ILogger>(context =>
{
return new Logger(context.ImplementationType.Name);
});
这篇关于如何使用Simple Injector返回基于其父对象的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!