Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Singleton Pattern and MEF

Tags:

c#

singleton

mef

I have a question about the Singleton Pattern and MEF. I'm new in implementing MEF Plugins and I haven't found an answer.

Is it possible to provide only one instance of a class through a MEF implemented Plugin?

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?

like image 748
subprime Avatar asked Jan 25 '12 21:01

subprime


1 Answers

Yes it is possible to do so.

By default, MEF will always return the same instance of a class when it fill your imports. 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.

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.

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. You can also find blogs on the subject by searching for : "MEF Creation Policy".

like image 90
Gilles Avatar answered Oct 08 '22 23:10

Gilles