Usage of binding to constants and binding to types in scopes with Ninject

后端 未结 1 773
说谎
说谎 2021-01-04 17:12

Which way of creating bindings of single object to interface is preferable, when and why:

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

相关标签:
1条回答
  • 2021-01-04 17:41

    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. 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()

    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
    
    0 讨论(0)
提交回复
热议问题