我使用的是用于.Net 3.5框架的NINObject2.0。我在单例绑定方面遇到了困难。
我有一个实现IInputReader的类UserInputReader。我只想创建这个类的一个实例。
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;
}
}如果我将构造函数设为私有,它就会中断。我在这里做错了什么?
发布于 2010-04-06 06:24:21
当然,如果您将构造函数设为私有,它就会中断。你不能从你的类外部调用私有构造函数!
你正在做的就是你应该做的。测试它:
var reader1 = ninject.Get<IInputReader>();
var reader2 = ninject.Get<IInputReader>();
Assert.AreSame(reader1, reader2);您不需要静态字段来获取实例单例。如果您使用的是IoC容器,则应该通过该容器获取所有实例。
如果您do需要公共静态字段(不确定这样做是否有充分的理由),您可以将类型绑定到它的值,如下所示:
Bind<UserInputReader>().ToConstant(UserInputReader.Instance);编辑:要指定在UserInputReader的构造函数中使用的IDictionary<ActionInputType, Keys>,可以使用WithConstructorArgument方法:
Bind<UserInputReader>().ToSelf()
.WithConstructorArgument("keyMapping", Constants.DEFAULT_KEY_MAPPING)
.InSingletonScope();发布于 2010-04-06 06:24:16
IInputReader不声明实例字段,也不能声明它,因为接口不能有字段或静态字段,甚至不能有静态属性(或静态方法)。
绑定类不能知道它要查找实例字段(除非它使用反射)。
https://stackoverflow.com/questions/2581521
复制相似问题