我在.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