Với cả hai công trình bạn thực hiện như nhau. Tuy nhiên, trong phương thức tiếp cận thứ hai của đối tượng Foo
đơn lẻ được hoãn lại cho đến cuộc gọi Get
đầu tiên. Hãy để tôi minh họa rằng với một ví dụ nhỏ. Hãy xem xét các ứng dụng sau:
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");
}
}
này giúp bạn kết quả:
Starting the app
Foo constructor called
Binding complete
Stopping the app
Bây giờ, chúng ta hãy thay thế ToConstant
cuộc gọi với 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");
}
}
Bây giờ đầu ra là:
Starting the app
Binding complete
Foo constructor called
Stopping the app
Cảm ơn bạn đã giải thích và ví dụ của bạn. – Srv19