С обеими конструкциями вы делаете то же самое.Однако в последнем подходе построение одиночного объекта Foo
откладывается до первого вызова Get
.Позвольте мне проиллюстрировать это небольшим примером.Рассмотрим следующее приложение:
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");
}
}
Это даст вам вывод:
Starting the app
Foo constructor called
Binding complete
Stopping the app
Теперь давайте заменим вызов 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");
}
}
Теперь вывод:
Starting the app
Binding complete
Foo constructor called
Stopping the app