MEF:如何从导出的对象导入?
我创建了一个 MEF 插件控件,并将其导入到我的应用程序中。现在,我希望插件能够从应用程序导入部件。我不知道如何在插件中设置目录,以便它可以找到应用程序的导出。有人能告诉我这是怎么做到的吗?下面是我的代码,当我尝试使用当前执行的程序集创建 AssemblyCatalog 时,该代码不起作用。
[Export(typeof(IPluginControl))]
public partial class MyPluginControl : UserControl, IPluginControl
[Import]
public string Message { get; set; }
public MyPluginControl()
{
InitializeComponent();
Initialize();
}
private void Initialize()
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
CompositionContainer container = new CompositionContainer(catalog);
try
{
container.ComposeParts(this);
}
catch (CompositionException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
I have created a MEF plugin control that I import into my app. Now, I want the plugin to be able to import parts from the app. I can't figure how setup the catalog in the plugin, so that it can find the exports from the app. Can somebody tell me how this is done? Below is my code which doesn't work when I try to create an AssemblyCatalog with the current executing assembly.
[Export(typeof(IPluginControl))]
public partial class MyPluginControl : UserControl, IPluginControl
[Import]
public string Message { get; set; }
public MyPluginControl()
{
InitializeComponent();
Initialize();
}
private void Initialize()
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
CompositionContainer container = new CompositionContainer(catalog);
try
{
container.ComposeParts(this);
}
catch (CompositionException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不需要这样做。
只需确保导入此插件时使用的目录包含主应用程序的程序集即可。
当 MEF 构建您的类型以便导出它(以实现其他地方的
IPluginControl
导入)时,它已经为您编写了这部分 - 并且在那时,将导入“Message”字符串(尽管,您很可能应该为该“消息”分配一个名称,或者某种自定义类型 - 否则,它只会导入一个字符串,并且您只能在应用程序中的任何位置使用单个“字符串”导出)。当 MEF 组合部件时,它会查找与指定类型匹配的所有类型(在本例中是
IPluginControl
),实例化单个对象,填充该对象的任何[Import]
要求(其中这就是为什么您不需要在构造函数中编写它),然后将其分配给导入该类型的任何对象。You don't need to do this.
Just make sure that the catalog you're using when you import this plugin includes the main application's assembly.
When MEF constructs your type in order to export it (to fulfill the
IPluginControl
import elsewhere), it'll already compose this part for you - and at that point, will import the "Message" string (though, you most likely should assign a name to that "message", or a custom type of some sort - otherwise, it'll just import a string, and you can only use a single "string" export anywhere in your application).When MEF composes parts, it finds all types matching the specified type (in this case
IPluginControl
), instantiates a single object, fills any[Import]
requirements for that object (which is why you don't need to compose this in your constructor), then assigns it to any objects importing the type.