Ninject:Singleton绑定语法?

Nic*_*ner 9 c# dependency-injection ninject

我正在使用Ninject 2.0作为.Net 3.5框架.我对单例绑定有困难.

我有一个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;
        }
}
Run Code Online (Sandbox Code Playgroud)

如果我将该构造函数设为私有,则会中断.我在这做错了什么?

R. *_*des 18

当然,如果你将构造函数设为私有,它就会中断.你不能从课外召唤私人施工人员!

你正在做的正是你应该做的.测试一下:

var reader1 = ninject.Get<IInputReader>();
var reader2 = ninject.Get<IInputReader>();
Assert.AreSame(reader1, reader2);
Run Code Online (Sandbox Code Playgroud)

您不需要静态字段来获取实例单例.如果您正在使用IoC容器,则应通过容器获取所有实例.

如果你确实需要公共静态字段(不确定是否有充分的理由),可以将类型绑定到其值,如下所示:

Bind<UserInputReader>().ToConstant(UserInputReader.Instance);
Run Code Online (Sandbox Code Playgroud)

编辑:要指定IDictionary<ActionInputType, Keys>要在构造函数中UserInputReader使用,可以使用以下WithConstructorArgument方法:

Bind<UserInputReader>().ToSelf()
     .WithConstructorArgument("keyMapping", Constants.DEFAULT_KEY_MAPPING)
     .InSingletonScope();
Run Code Online (Sandbox Code Playgroud)