我正在使用MEF2 (Microsoft.Composition)创建一个具有多个插件的应用程序。这些插件应该导入一些公共对象,并且它们都应该共享这个对象的相同实例……所以一个典型的单例。
然而,当我将这个公共对象[Import]到我的插件中时,它们都得到了自己的副本,而不是共享的副本。
在.NET框架MEF1中,默认情况下所有对象都是作为单例创建的。这似乎不是.NET核心MEF2的情况。
我怎样才能确保我所有的插件都得到了我的通用对象的相同的单例实例?
示例代码
启动
static void Main(string[] args) {
ContainerConfiguration containerConfig = new ContainerConfiguration()
.WithAssembly(Assembly.GetExecutingAssembly())
.WithAssembly(typeof(ICommonObject).Assembly);
using (CompositionHost container = containerConfig.CreateContainer()) {
_mainApp = container.GetExport<MainApp>();
_mainApp.Start();
}
}MainApp
[Export(typeof(MainApp))]
public class MainApp {
[Import] public ICommonObject CommonObject { get; set; }
[ImportMany] public IEnumerable<IPlugin> Plugins { get; set; }
public void Start() {
CommonObject.SomeValue = "foo";
Console.WriteLine("SomeValue (from MainApp): " + CommonObject.SomeValue);
foreach (IPlugin plugin in Plugins) {
plugin.Start();
}
}
}插件
[Export(typeof(IPlugin))]
public class SomePlugin : IPlugin {
[Import] public ICommonObject CommonObject { get; set; }
public void Start() {
Console.WriteLine("SomeValue (from plugin): " + CommonObject.SomeValue);
}
}输出
SomeValue (from MainApp): foo
SomeValue (from plugin):发布于 2018-08-30 05:01:03
经过反复试验,我似乎终于找到了自己的解决方案。
诀窍似乎是使用ConventionBuilder。这有一个名为.Shared()的扩展方法,它使从特定类型派生的所有对象都变成一个单例。
对于我的代码示例,只需将以下代码添加到启动代码的顶部:
ConventionBuilder conventions = new ConventionBuilder();
conventions.ForTypesDerivedFrom<ICommonObject>()
.Export<ICommonObject>()
.Shared();
ContainerConfiguration containerConfig = new ContainerConfiguration()
.WithAssembly(Assembly.GetExecutingAssembly(), conventions);由于某些原因,实现ICommonObject的对象甚至不需要[Export]属性。在任何情况下,示例的输出现在都是:
SomeValue (from MainApp): foo
SomeValue (from plugin): foohttps://stackoverflow.com/questions/52084994
复制相似问题