创建单个对象到接口的绑定的哪种方式更可取,何时以及为什么:
Kernel.Bind<IFoo>().ToConstant(new Foo());
Run Code Online (Sandbox Code Playgroud)
要么
Kernel.Bind<IFoo>().To(typeof(Foo)).InSingletonScope();
Run Code Online (Sandbox Code Playgroud)
或者,如果两种方式都不正确并且更好地避免,应该使用什么呢?
Jer*_*oen 15
使用这两种结构,您可以完成相同的操作 但是,在后一种方法中,单个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");
}
}
Run Code Online (Sandbox Code Playgroud)
这可以获得输出:
Starting the app
Foo constructor called
Binding complete
Stopping the app
Run Code Online (Sandbox Code Playgroud)
现在,让我们用.替换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");
}
}
Run Code Online (Sandbox Code Playgroud)
现在的输出是:
Starting the app
Binding complete
Foo constructor called
Stopping the app
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2252 次 |
| 最近记录: |