本文介绍了设置Ninject单身人士的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类(MyFacade),我用Ninject注入了参数:

I have a class (MyFacade) that I injected parameter(s) with Ninject:

class MyFacade
{
    IDemoInterface demo;

    public MyFacade(IDemoInterface demo)
    {
        this.demo = demo;
    }

    public void MyMethod()
    {
        Console.WriteLine(demo.GetInfo());
    }
}

当然,我必须设置Ninject来注入参数(IDemoInterface)的适当实现

Of course, I have to setup the Ninject to inject the appropiate implementation of my parameter (IDemoInterface)

我知道,我可以通过执行kernel.Get<MyFacade>();来实例化MyFacade对象,而无需进行其他设置.目前,我的外观没有接口(因为这是我唯一的实现,也许我会为标准提议添加其接口)

I know, I can instantiate MyFacade object by doing kernel.Get<MyFacade>(); without setting anything else. Currently my facade doesn't have an interface (because it is my only implementation, maybe I will add its interface for standard proposes)

如果我想使外观立面单调,我知道两种方法:创建一个空的构造函数并通过执行kernel.Get<IDemoInterface>();或通过设置Ninject来传递参数,例如:kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();

if I want to make this facade singlenton, I know two ways: create a empty constructor and pass a parameter by doing this kernel.Get<IDemoInterface>(); or by setup Ninject like: kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();

第二种方法看起来更好,但是您知道以其他方式设置它的其他方法吗?

The second one look a better approach, but do you know any other way to setup it in a singleton way?

推荐答案

设置绑定时,需要绑定依赖项.最好在绑定中设置依赖项,而不是在构造函数中执行kernel.Get<T>().您正在使用IOC,因此请利用您正在使用的框架为您进行注入.

When setting up your bindings, you need to bind your dependencies. It is always better to setup your dependencies in your bindings, as opposed to doing a kernel.Get<T>() in a constructor. You are using IOC, so leverage the framework you are using to do the injection for you.

在第二个示例绑定中,缺少的是IDemoInterface中的绑定.您的绑定应如下所示:

In your second example binding, what you are missing is binding in your IDemoInterface. Your bindings should look like this:

//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();

这篇关于设置Ninject单身人士的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:29