使用绑定到常量并使用Ninject绑定到范围中的类型

创建单个对象到接口的绑定的哪种方式更可取,何时以及为什么:

Kernel.Bind().ToConstant(new Foo()); 

要么

 Kernel.Bind().To(typeof(Foo)).InSingletonScope(); 

或者,如果两种方式都不正确并且更好地避免,那么应该使用什么呢?

使用这两种结构,您可以完成相同的操作 但是,在后一种方法中,单个Foo对象的构造将推迟到第一个Get调用。 让我用一个小例子来说明这一点。 考虑以下应用程序:

 class Program { static void Main(string[] args) { Console.WriteLine("Starting the app"); IKernel kernel = new StandardKernel(); kernel.Bind().ToConstant(new Foo()); Console.WriteLine("Binding complete"); kernel.Get(); Console.WriteLine("Stopping the app"); } } public interface IFoo { } public class Foo : IFoo { public Foo() { Console.WriteLine("Foo constructor called"); } } 

这可以获得输出:

 Starting the app Foo constructor called Binding complete Stopping the app 

现在,让我们用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().To(typeof(Foo)).InSingletonScope(); Console.WriteLine("Binding complete"); kernel.Get(); Console.WriteLine("Stopping the app"); } } public interface IFoo { } public class Foo : IFoo { public Foo() { Console.WriteLine("Foo constructor called"); } } 

现在输出是:

 Starting the app Binding complete Foo constructor called Stopping the app