gpt4 book ai didi

C# 单例模式和 MEF

转载 作者:太空狗 更新时间:2023-10-29 17:34:25 24 4
gpt4 key购买 nike

我有一个关于单例模式和 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 所说的共享创建策略。

如果您不希望您的导入来自同一个实例,您需要在您的属性中指定它:

[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
}

但是没有必要,Shared(单例)已经是默认值了。

这里是 MEF 文档的链接:http://mef.codeplex.com/wikipage?title=Parts%20Lifetime这解释了我刚才所说的。您还可以通过搜索“MEF 创建策略”找到有关该主题的博客。

关于C# 单例模式和 MEF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9010437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com