Ninject:Singleton绑定语法?

时间:2010-04-05 22:19:58

标签: 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;
        }
}

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

2 个答案:

答案 0 :(得分:18)

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

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

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

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

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

Bind<UserInputReader>().ToConstant(UserInputReader.Instance);

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

Bind<UserInputReader>().ToSelf()
     .WithConstructorArgument("keyMapping", Constants.DEFAULT_KEY_MAPPING)
     .InSingletonScope();

答案 1 :(得分:0)

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

Bind类无法知道找到Instance字段(除非它使用反射)。