完全懒惰的单身,我有以下代码实现我一般单供应商:如何创建泛型
public sealed class Singleton<T> where T : class, new()
{
Singleton()
{
}
public static T Instance
{
get { return SingletonCreator.instance; }
}
class SingletonCreator
{
static SingletonCreator()
{
}
internal static readonly T instance = new T();
}
}
这个样本是从2篇拍摄,我合并的代码让我我想要的东西:
http://www.yoda.arachsys.com/csharp/singleton.html and http://www.codeproject.com/Articles/11111/Generic-Singleton-Provider。
这是我尝试使用上面的代码:
public class MyClass
{
public static IMyInterface Initialize()
{
if (Singleton<IMyInterface>.Instance == null // Error 1
{
Singleton<IMyInterface>.Instance = CreateEngineInstance(); // Error 2
Singleton<IMyInterface>.Instance.Initialize();
}
return Singleton<IMyInterface>.Instance;
}
}
和接口:
public interface IMyInterface
{
}
在Error 1
的错误是:
'MyProject.IMyInterace' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'MyProject.Singleton<T>'
在Error 2
错误是:
Property or indexer 'MyProject.Singleton<MyProject.IMyInterface>.Instance' cannot be assigned to -- it is read only
我该如何解决这个问题,以便它符合上面提到的两篇文章?任何其他想法或建议表示赞赏。
我的实现是否打破Singleton模式?
单身已死; [生命期/范围应该由依赖注入容器来处理](http://stackoverflow.com/questions/4484619/does-mef-lend-any-value-to-the-singleton-pattern/4484889#4484889)。 – 2012-03-31 12:18:27
当然。创建和控制单个对象的生命周期是单身人士的责任,但是您正在尝试为该类别外的单身人员类的实例属性赋值。从我看到的依赖注入和基于接口的编程中,你真正想要做什么。 Singleton只在尝试使用sparce资源(例如数据库连接)时非常有用,并且应谨慎使用(甚至可以避免) – 2012-03-31 12:22:12
我正在尝试为我的web mvc应用程序创建引擎,它处理我需要的所有内容,依赖注入,我只希望这个实例的一个实例存在。 – 2012-03-31 12:36:28