C# Singleton Pattern and MEF

爱⌒轻易说出口 提交于 2019-12-04 02:40:51

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".

Mudx

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.

So you are creating a singleton per T type that you use.

The best way for singleton is something like this:

public class Logger {
    public static readonly Logger Instace;

    static Logger() {
        Instace = new Logger();
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!