使用Ninject绑定到常量和绑定到范围中的类型的用法 [英] Usage of binding to constants and binding to types in scopes with Ninject
问题描述
哪种方式创建单个对象到接口的绑定是首选,何时以及为什么:
Which way of creating bindings of single object to interface is preferable, when and why:
Kernel.Bind<IFoo>().ToConstant(new Foo());
或
Kernel.Bind<IFoo>().To(typeof(Foo)).InSingletonScope();
或者,如果两种方法都不正确并且最好避免,应该使用什么替代方法?
Or, if both ways are incorrect and better to be avoided, what should be used instead?
推荐答案
使用这两种构造,您可以完成相同的工作.但是,在后一种方法中,将单个Foo
对象的构造推迟到第一次Get
调用之前.
让我用一个小例子来说明这一点.考虑以下应用程序:
With both constructions you accomplish the same. However, in the latter approach construction of the single Foo
object is deferred until the first Get
call.
Let me illustrate that with a little example. Consider the following application:
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()
Now, let's replace the ToConstant
call with 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
这篇关于使用Ninject绑定到常量和绑定到范围中的类型的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!