简体   繁体   English

C#Singleton模式和MEF

[英]C# Singleton Pattern and MEF

I have a question about the Singleton Pattern and MEF. 我对Singleton Pattern和MEF有疑问。 I'm new in implementing MEF Plugins and I haven't found an answer. 我是实施MEF插件的新手,我还没有找到答案。

Is it possible to provide only one instance of a class through a MEF implemented Plugin? 是否可以通过MEF实现的插件只提供一个类的实例?

My old class is something like this: 我的老班是这样的:


  #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

Can someone provide me an example? 有人可以给我一个例子吗?

Yes it is possible to do so. 是的,有可能这样做。

By default, MEF will always return the same instance of a class when it fill your imports. 默认情况下,MEF在填充导入时将始终返回相同的类实例。 So technically you do not have to do anything if you want it to be a singleton. 所以从技术上讲,如果你想让它成为一个单身人士,你就不需要做任何事情。 This is what MEF calls a Shared Creation Policy. 这就是MEF所谓的共享创建策略。

If you do not want your imports to come from the same instance, you need to specify it, either in your attributes likewise: 如果您不希望导入来自同一实例,则需要在属性中指定它:

[Import(RequiredCreationPolicy = CreationPolicy.NonShared)]
public MyClass : IMyInterface

Or you can override your own CompositionContainer so that will create NonShared instances by default. 或者您可以覆盖自己的CompositionContainer,以便默认情况下创建NonShared实例。

Note that you can also explicitly specify that you want a Shared Creation Policy (singletons): 请注意,您还可以明确指定您需要共享创建策略(单例):

[Import(RequiredCreationPolicy = CreationPolicy.Shared)]
public MyClass : IMyInterface
{
    public MyClass() { } // you can have a public ctor, no need to implement the singleton pattern 
}

But it is not necessary as Shared (singleton) is already the default value. 但是没有必要,因为共享(单例)已经是默认值。

Here is a link to MEF's documentation : http://mef.codeplex.com/wikipage?title=Parts%20Lifetime which explains what I just talked about. 以下是MEF文档的链接: http//mef.codeplex.com/wikipage? title = Items% 20Lifetime ,它解释了我刚刚谈到的内容。 You can also find blogs on the subject by searching for : "MEF Creation Policy". 您还可以通过搜索“MEF创建策略”找到有关该主题的博客。

Very bad practice ! 非常糟糕的做法! use static constructor: guaranteed to be executed exactly once 使用静态构造函数:保证只执行一次

Please note that for each T that you create, the CLR will copy the static data for the new T . 请注意,对于您创建的每个T ,CLR将复制新T的静态数据。

So you are creating a singleton per T type that you use. 因此,您要创建每个T类型的单例。

The best way for singleton is something like this: 单身人士的最佳方式是这样的:

public class Logger {
    public static readonly Logger Instace;

    static Logger() {
        Instace = new Logger();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM