我有一个类 ( MyFacade
),我用 Ninject
注入(inject)了参数:
class MyFacade
{
IDemoInterface demo;
public MyFacade(IDemoInterface demo)
{
this.demo = demo;
}
public void MyMethod()
{
Console.WriteLine(demo.GetInfo());
}
}
当然,我必须设置 Ninject
注入(inject)我的参数的适当实现(IDemoInterface
)
我知道,我可以实例化MyFacade
通过做对象kernel.Get<MyFacade>();
无需设置任何其他内容。目前我的门面没有接口(interface)(因为它是我唯一的实现,也许我会为标准建议添加它的接口(interface))
如果我想让这个门面成为单例,我知道两种方法:创建一个空的构造函数并通过这样做传递一个参数kernel.Get<IDemoInterface>();
或者像这样设置 Ninject:kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();
第二种方法看起来更好,但您知道以单例方式设置它的任何其他方法吗?
最佳答案
设置绑定(bind)时,您需要绑定(bind)依赖项。最好在绑定(bind)中设置依赖项,而不是执行 kernel.Get<T>()
在构造函数中。您正在使用 IOC,因此请利用您正在使用的框架为您进行注入(inject)。
在您的第二个示例绑定(bind)中,您缺少的是在您的 IDemoInterface
中进行绑定(bind).您的绑定(bind)应如下所示:
//bind the dependency to the implementation.
kernel.Bind<IDemoInterface>().To<DemoInterface>();
//since you bound your dependency, ninject should now have
// all the dependencies required to instantiate your `MyFacade` object.
kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();
关于c# - 设置 Ninject 单例的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21706436/