我有关于Singleton模式和MEF的问题.我是新的实施MEF插件,我还没有找到答案.
通过MEF实现的插件,可以提供一个类的一个实例吗?
我的老班是这样的:
#region Singleton /// /// This class provide a generic and thread-safe interface for Singleton classes. /// /// The specialized singleton which is derived /// from SingletonBase<T> public abstract class Base where T : Base { /* the lock object */ private static object _lock = new object(); /* the static instance */ private static T _instance = null; /// /// Get the unique instance of . /// This property is thread-safe! /// public static T Instance { get { if (_instance == null) { lock (_lock) { if (_instance == null) { /* Create a object without to use new (where you need a public ctor) */ object obj = FormatterServices.GetUninitializedObject(typeof(T)); if (obj != null) // just 4 safety,but i think obj == null shouldn't be possible { /* an extra test of the correct type is redundant,* because we have an uninitialised object of type == typeof(T) */ _instance = obj as T; _instance.Init(); // now the singleton will be initialized } } } } else { _instance.Refresh(); // has only effect if overridden in sub class } return _instance; } } /// /// Called while instantiation of singleton sub-class. /// This could be used to set some default stuff in the singleton. /// protected virtual void Init() { } /// /// If overridden this will called on every request of the Instance but /// the instance was already created. Refresh will not called during /// the first instantiation,for this will call Init. /// protected virtual void Refresh() { } } #endregion #region class public class xy : Base { private bool run; public xy() { this.run = false; } public bool isRunning() { return this.run; } public void start() { // Do some stuff this.run = true; } } #endregion
有人可以给我一个例子吗?
解决方法
是的,可以这样做.
默认情况下,当MEF填充导入时,MEF将始终返回类的同一个实例.所以在技术上你不需要做任何事情,如果你希望它是一个单身人士.这就是MEF所说的共享创建政策.
如果您不希望导入来自同一个实例,则需要在属性中指定它:
[Import(requiredCreationPolicy = CreationPolicy.NonShared)] public MyClass : IMyInterface
或者您可以覆盖自己的CompositionContainer,以便默认情况下创建NonShared实例.
请注意,您还可以明确指定您想要共享创建策略(单身):
[Import(requiredCreationPolicy = CreationPolicy.Shared)] public MyClass : IMyInterface { public MyClass() { } // you can have a public ctor,no need to implement the singleton pattern }
但是,共享(单例)已经是默认值不是必需的.
这是MEF文档的链接:http://mef.codeplex.com/wikipage?title=Parts%20Lifetime,它解释了我刚刚谈到的内容.您还可以通过搜索:“MEF创建策略”来查找有关此主题的博客.