我正在为 .Net 3.5 框架使用 Ninject 2.0。我在单例绑定(bind)方面遇到困难。
我有一个类UserInputReader
,它实现了IInputReader
。我只想创建此类的一个实例。
public class MasterEngineModule : NinjectModule
{
public override void Load()
{
// using this line and not the other two makes it work
//Bind<IInputReader>().ToMethod(context => new UserInputReader(Constants.DEFAULT_KEY_MAPPING));
Bind<IInputReader>().To<UserInputReader>();
Bind<UserInputReader>().ToSelf().InSingletonScope();
}
}
static void Main(string[] args)
{
IKernel ninject = new StandardKernel(new MasterEngineModule());
MasterEngine game = ninject.Get<MasterEngine>();
game.Run();
}
public sealed class UserInputReader : IInputReader
{
public static readonly IInputReader Instance = new UserInputReader(Constants.DEFAULT_KEY_MAPPING);
// ...
public UserInputReader(IDictionary<ActionInputType, Keys> keyMapping)
{
this.keyMapping = keyMapping;
}
}
如果我将该构造函数设为私有(private),它就会中断。我在这里做错了什么?
最佳答案
当然,如果您将构造函数设为私有(private),它就会中断。您不能从类外部调用私有(private)构造函数!
您所做的正是您应该做的。测试一下:
var reader1 = ninject.Get<IInputReader>();
var reader2 = ninject.Get<IInputReader>();
Assert.AreSame(reader1, reader2);
您不需要静态字段来获取实例单例。如果您使用的是 IoC 容器,则应通过该容器获取所有实例。
如果您确实想要公共(public)静态字段(不确定是否有充分的理由),您可以将类型绑定(bind)到它的值,如下所示:
Bind<UserInputReader>().ToConstant(UserInputReader.Instance);
编辑:指定 IDictionary<ActionInputType, Keys>
在 UserInputReader
的构造函数中使用, 您可以使用 WithConstructorArgument
方法:
Bind<UserInputReader>().ToSelf()
.WithConstructorArgument("keyMapping", Constants.DEFAULT_KEY_MAPPING)
.InSingletonScope();
关于c# - Ninject:单例绑定(bind)语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2581521/