c# - 设置 Ninject 单例的方法

标签 c# singleton ninject

我有一个类 ( 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/

相关文章:

c# - Microsoft 是否修复了 .NET 4.0 中的 Linq to Entities 性能问题?

ios - swift中静态函数和单例类的区别

caSTLe-windsor - 无需配置即可自动注册所有内容(非通用)的 IoC 容器(程序集到程序集)

c# - 如何在 Visual Studio 2010 中删除/卸载项目模板

c# - 从 Azure WebJob 运行 Python 脚本

c# - UITableView 标题和文本颜色

c++ - 陷阱 : The static stack variable Singleton class

java - 单例类的公共(public)方法应该同步吗?

asp.net-mvc - Ninject 和连接字符串

c# - Ninject - 创建自定义 NinjectWebServiceHost