简体   繁体   English

使用绑定到常量并使用Ninject绑定到作用域中的类型

[英]Usage of binding to constants and binding to types in scopes with Ninject

Which way of creating bindings of single object to interface is preferable, when and why: 创建单个对象到接口的绑定的哪种方式更可取,何时以及为什么:

Kernel.Bind<IFoo>().ToConstant(new Foo());

or 要么

Kernel.Bind<IFoo>().To(typeof(Foo)).InSingletonScope();

Or, if both ways are incorrect and better to be avoided, what should be used instead? 或者,如果两种方式都不正确并且更好地避免,应该使用什么呢?

With both constructions you accomplish the same. 使用这两种结构,您可以完成相同的操作 However, in the latter approach construction of the single Foo object is deferred until the first Get call. 但是,在后一种方法中,单个Foo对象的构造将推迟到第一个Get调用。 Let me illustrate that with a little example. 让我用一个小例子来说明这一点。 Consider the following application: 考虑以下应用程序:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting the app");

        IKernel kernel = new StandardKernel();
        kernel.Bind<IFoo>().ToConstant(new Foo());

        Console.WriteLine("Binding complete");

        kernel.Get<IFoo>();

        Console.WriteLine("Stopping the app");
    }
}

public interface IFoo
{
}

public class Foo : IFoo
{
    public Foo()
    {
        Console.WriteLine("Foo constructor called");
    }
}

This gets you the output: 这可以获得输出:

Starting the app
Foo constructor called
Binding complete
Stopping the app

Now, let's replace the ToConstant call with To(typeof(Foo)).InSingletonScope() 现在,让我们用To(typeof(Foo)).InSingletonScope()替换ToConstant调用To(typeof(Foo)).InSingletonScope()

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting the app");

        IKernel kernel = new StandardKernel();
        kernel.Bind<IFoo>().To(typeof(Foo)).InSingletonScope();

        Console.WriteLine("Binding complete");

        kernel.Get<IFoo>();

        Console.WriteLine("Stopping the app");
    }
}

public interface IFoo
{
}

public class Foo : IFoo
{
    public Foo()
    {
        Console.WriteLine("Foo constructor called");
    }
}

Now the output is: 现在的输出是:

Starting the app
Binding complete
Foo constructor called
Stopping the app

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM