Which way of creating bindings of single object to interface is preferable, when and why:
Kernel.Bind().ToConstant(new Foo());
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