我在.NET 3.5框架中使用Ninject 2.0。我与单身绑定有困难。Ninject:Singleton绑定语法?
我有一个类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;
}
}
如果我使该构造函数为私有,它会中断。我在这里做错了什么?
对单身一些有趣的变化:HTTP:// w^ww.yoda.arachsys.com/csharp/singleton.html – mcliedtk 2010-04-05 22:26:55
如果构造函数在同一个程序集中,则可以将其构造成内部而不是私有的。如果您担心访问该构造函数的其他程序集的代码,那么也许该广告会有一点安全性。 – jpierson 2011-10-24 20:23:12
'绑定()。到()。InSingletonScope()' –
Jaider
2014-04-09 16:56:23