我有以下代码
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
}
}
Run Code Online (Sandbox Code Playgroud)
但似乎提供商采用了IContext,我放了xxxxxx.不应该使用IContext从我引导并从内核创建Something.cs时使用.Provider上的no参数Create方法在哪里??? (我来自Guice的土地观点,它将被编码如上).
所以问题是如何正确地做到这一点?
谢谢,迪恩
Rem*_*oor 12
您似乎正在尝试将提供程序用作代码中的工厂.
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>();
Run Code Online (Sandbox Code Playgroud)
你想要的是你的编码器中的工厂,它创建了一个实例WindowHandler.因此,创建一个接口来创建这样的实例:
public interface IWindowHandlerFactory
{
WindowHandler Create();
}
Bind<IWindowHandlerFactory>().ToFactory();
Run Code Online (Sandbox Code Playgroud)
或者,您可以在Func<WindowHandler>不添加配置的情 但在我看来,这没有什么意义.
注意:所有这些都需要Ninject.Extensions.Factory作为Nuget的预发布3.0.0-rc2.
另见:http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/