Ninject:单例绑定语法? [英] Ninject: Singleton binding syntax?

查看:80
本文介绍了Ninject:单例绑定语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Ninject 2.0用于.Net 3.5框架.我在单例装订上遇到困难.

I'm using Ninject 2.0 for the .Net 3.5 framework. I'm having difficulty with singleton binding.

我有一个实现IInputReader的类UserInputReader.我只希望创建此类的一个实例.

I have a class UserInputReader which implements IInputReader. I only want one instance of this class to ever be created.

 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;
        }
}

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

If I make that constructor private, it breaks. What am I doing wrong here?

推荐答案

如果将构造函数设为私有,当然会中断.您不能从班级外部调用私有构造函数!

Of course it breaks if you make the constructor private. You can't call private constructors from outside your class!

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

What you're doing is exactly what you're supposed to do. Test it:

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

您不需要静态字段即可获取实例单例.如果您使用的是IoC容器,则应通过该容器获取所有实例.

You don't need the static field to get the instance singleton. If you're using an IoC container, you should get all your instances through the container.

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

If you do want the public static field (not sure if there is a good reason for that), you can bind the type to its value, like this:

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

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

EDIT: To specify the IDictionary<ActionInputType, Keys> to use in the constructor of UserInputReader, you can use the WithConstructorArgument method:

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

这篇关于Ninject:单例绑定语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆