【发布时间】:2012-03-31 21:01:52
【问题描述】:
我的通用单例提供程序有以下代码实现:
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 和 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
我该如何解决这个问题,使其符合上述 2 篇文章?任何其他想法或建议表示赞赏。
我的实现是否打破了单例模式?
【问题讨论】:
-
当然。创建和控制单个对象的生命周期是单例的责任,但您试图为该类的单例类的实例属性分配一个值。从我看到的情况来看,您真正想做的是依赖注入和基于接口的编程。单例仅在您尝试使用稀有资源(例如数据库连接)时才有用,应谨慎使用(甚至避免使用)
-
我正在尝试为我的 web mvc 应用程序创建一个引擎,它可以处理我需要的一切,依赖注入,并且我只希望该实例存在 1 个实例。
-
然后接吻。保持愚蠢简单。在你的应用引擎类中编写一个普通的单例,不要为泛型而烦恼。太过分了。
-
@T.Fabre:我猜你说得有道理。如果我的应用程序中需要另一个不同对象的另一个单例实例?
标签: c# asp.net .net c#-4.0 singleton