Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 660
Srv19 Avatar asked Mar 13 '12 10:03

Srv19


1 Answers

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
like image 90
Jeroen Avatar answered Oct 20 '22 16:10

Jeroen