我有以下代码
public class Something {
[Inject]
public Configuration config {get;set;} //singleton
[Inject]
public Provider<WindowHandler> windowsProvider { get; set; } //NOT singleton
public void Search(string text) {
WindowHandler handler = windowsProvider.Create(xxxxxx);
//use the new handler that was created
}
}
但看起来 Provider 在我放置 xxxxxx 的地方采用了 IContext。不应该使用我从内核引导并创建 Something.cs 时的 IContext 吗? Provider 上的无参数 Create 方法在哪里??? (我来自 Guice land 的观点,它的编码方式与上面类似)。
所以问题是我该如何正确地做到这一点?
谢谢,
院长
您似乎正在尝试在代码中使用提供程序作为工厂。
Ninject 术语中的提供者是一个工厂,提供给 Ninject 来创建专门创建的对象。因此,它获得解析上下文,该上下文可用于创建不同的实例,具体取决于实例注入的位置。
public class FooProvider : Provider<IFoo>
{
public override IFoo CreateInstance(IContext ctx)
{
// add here your special IFoo creation code
return new Foo();
}
}
kernel.Bind<IFoo>().ToProvider<FooProvider>();
您想要的是编码器中的一个工厂,它创建一个实例WindowHandler
。因此创建一个接口来创建实例,如下所示:
public interface IWindowHandlerFactory
{
WindowHandler Create();
}
Bind<IWindowHandlerFactory>().ToFactory();
或者你可以注射Func<WindowHandler>
无需添加配置。但这在我看来意义不大。
注意:所有这些都需要 Nuget 提供的 Ninject.Extensions.Factory 作为预发行版 3.0.0-rc2。
也可以看看:http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/ http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)