我有一个只BillLines
创建一个实例的要求,这对于单例模式当然是完美的。
看着Jon的Skeet的帖子,我不太了解在哪里创建我的“新”对象(即有用的对象,而不是抽象的Singleton对象)。
这对您来说是否正确?
public sealed class ContextSingleton
{
private static readonly Lazy<ContextSingleton> Lazy =
new Lazy<ContextSingleton>(() => new ContextSingleton());
public static ContextSingleton Instance { get { return Lazy.Value; } }
private ContextSingleton()
{
}
//Is this correct? Where should I 'new' this?
public readonly IBillLineEntities Context = new BillLines.BillLines();
}
像这样被访问:
var contextSingleton = ContextSingleton.Instance.Context;
更新资料
我无权访问的内部,BillLines
但我需要确保仅存在其中一个实例。
感谢@JonSkeet和@RobH的评论,我走下了依赖注入路线。我选择了Ninject,并且按预期完成了工作:
public class NinjectBindings : NinjectModule
{
public override void Load()
{
Bind<IBillLineEntities>.To<BillLines.BillLines>().InSingletonScope();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句