C# Ninject:单例绑定语法?

C# Ninject:单例绑定语法?,c#,dependency-injection,ninject,C#,Dependency Injection,Ninject,我正在为.NET3.5框架使用Ninject 2.0。我在单例绑定方面有困难 我有一个类UserInputReader,它实现了IInputReader。我只想创建这个类的一个实例 public class MasterEngineModule : NinjectModule { public override void Load() { // using this line and not the other two makes

我正在为.NET3.5框架使用Ninject 2.0。我在单例绑定方面有困难

我有一个类
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;
        }
}
公共类MasterEngineModule:Ninject模块
{
公共覆盖无效负载()
{
//使用这条线而不是其他两条线可以使它工作
//Bind().ToMethod(context=>newuserinputreader(Constants.DEFAULT_KEY_MAPPING));
绑定()到();
Bind().ToSelf().InSingletonScope();
}
}
静态void Main(字符串[]参数)
{
IKernel ninject=新的标准内核(新的MasterEngineModule());
MasterEngine游戏=ninject.Get();
game.Run();
}
公共密封类UserInputReader:IInputReader
{
public static readonly IInputReader实例=新的UserInputReader(Constants.DEFAULT\u KEY\u映射);
// ...
公共用户输入头(IDictionary键映射)
{
this.keyMapping=keyMapping;
}
}

如果我将该构造函数设为私有,它将中断。我做错了什么?

IInputReader不声明实例字段,也不能声明实例字段,因为接口不能有字段或静态字段,甚至不能有静态属性(或静态方法)


Bind类无法知道它要查找实例字段(除非它使用反射)。

当然,如果将构造函数设置为私有,它会中断。您不能从类外调用私有构造函数

你所做的正是你应该做的。测试它:

var reader1 = ninject.Get<IInputReader>();
var reader2 = ninject.Get<IInputReader>();
Assert.AreSame(reader1, reader2);

关于单例的一些有趣的变化:如果构造函数在同一个程序集中,则可以将其设置为内部构造函数而不是私有构造函数。如果您担心来自访问该构造函数的其他程序集的代码,那么这可能会增加一点安全性。
Bind().To().InSingletonScope()
Ok,酷。但是UserInputReader的构造函数需要一个
IDictionary
。我如何在Ninject中指定它?@Rosarch:要么你在字典周围创建一个标记包装器,称它为
IActionKeyMap
或其他什么,然后使用它,要么你在评论中使用方法方法,或者你使用工具指定ctor参数(不记得确切的方式:(.Got:
。WithConstructorArgument(“keyMapping”),/*which*/);
是否有一行语法来执行
ninject.Get().DoSomething()
就像OP希望对
UserInputReader.Instance.DoSomething()执行的那样
Bind<UserInputReader>().ToConstant(UserInputReader.Instance);
Bind<UserInputReader>().ToSelf()
     .WithConstructorArgument("keyMapping", Constants.DEFAULT_KEY_MAPPING)
     .InSingletonScope();