【发布时间】:2014-03-29 04:07:42
【问题描述】:
我有一个定义范围的对象:
Bind<ISomething>().To<Something>().DefinesNamedScope(SomethingScope);
我还有一个创建 IAnotherThing 的自动生成工厂:
public interface IAnotherThingFactory
{
IAnotherThing CreateAnotherThing(ISomething x);
}
并绑定它:
Bind<IAnotherThingFactory>().ToFactory();
我想在 ISomething 的上下文中创建 IAnotherThing,所以我可以例如有一个 ISharedPrivateDependency 两者都获得相同的实例。但是,Something 必须不知道 IAnotherThing。这意味着,理想情况下,应该有一种方法可以从 ISomething 参数中提取上下文,并使用它来设置 IAnotherThing 的上下文。
为了获得这种行为,我必须定义什么绑定或编写代码?
我不想直接暴露内核,只暴露工厂。
在 cmets 之后编辑:
- 将 AnotherThing 的工厂放入 ISomething 可解决上下文问题,但会将 ISomething 暴露给 IAnotherThing。上面说明了对答案的要求:ISomething 一定不知道 IAnotherThing。所以这是不行的。
- 在 ISomething 接口中公开 Ninject-internals 也是如此。
【问题讨论】:
-
你能解释一下你所说的“上下文”是什么意思吗?您是否在问如何在
ISomething内部使用IAnotherThing而ISomething不知道IAnotherThing? .... -
Ninject Context Preservation Extension 意义上的上下文。
-
您是否明确需要使用
ToFactory()或者创建自己的工厂/供应商是否可行? -
我更喜欢 ToFactory(),但这不是必需的。
-
Ninject 没有检索先前实例化对象的上下文的功能。因此,如果不修改 ninject,就无法满足您的要求。
标签: c# dependency-injection scope ninject