[英]Usage of binding to constants and binding to types in scopes with Ninject
创建单个对象到接口的绑定的哪种方式更可取,何时以及为什么:
Kernel.Bind<IFoo>().ToConstant(new Foo());
要么
Kernel.Bind<IFoo>().To(typeof(Foo)).InSingletonScope();
或者,如果两种方式都不正确并且更好地避免,应该使用什么呢?
使用这两种结构,您可以完成相同的操作 但是,在后一种方法中,单个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()
替换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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.