2012-03-13 1 views

答えて

14

どちらの構造でも同じ結果が得られます。しかし、後者のアプローチでは、単一の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 

それでは、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"); 
    } 
} 

ToConstantコールに代わって今出力は次のとおりです。

Starting the app 
Binding complete 
Foo constructor called 
Stopping the app 
+0

あなたの説明と例をありがとう。 – Srv19

関連する問題