静态类的C#MEF用法 [英] C# MEF usage with static classes
问题描述
我的解决方案中有一个静态类,该类用于处理各种程序集.我想通过MEF链接它们,所以我在一个类中做了一个字段.
I have a static class in my solution which is used to work with various assemblies. I want to link them through MEF, so I made a field in a class.
[Import(typeof(A))]
static private A _a1;
然后我有一个方法,将程序集名称作为参数传递给该方法:
Then I have a method to which I pass assembly name as an argument:
public static A LoadPackage(string filePath)
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(filePath));
var _container = new CompositionContainer(catalog);
???
}
那么现在有没有办法从文件路径指定的程序集中导入类型?
So is there a way now to import type from assembly specified by filepath?
我做不到:
_container.ComposeParts(this);
由于类是静态的,我也不能这样做
since class is `static and neither can I do this
_container.ComposeParts(_a1);
(一开始可能是完全错误的),因为A
没有任何构造函数(因此_a1
为null)
(which might be completely wrong to begin with) since A
doesn't have any constructors(so _a1
is null)
推荐答案
事实证明,我正在寻找的方法是GetExportedValue
(是的,我忽略了基本功能):
Well it turns out that method I was looking for is GetExportedValue
(yeah, I overlooked basic functionality):
static private A _a1;
public static A LoadPackage(string filePath)
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(filePath));
var _container = new CompositionContainer(catalog);
_a1 = _container.GetExportedValue<A>();
}
然后我就把自己的领域填满了(以防万一,我已经将它移到另一个类了,现在看起来很整洁)
And I got my field filled (just in case, I already moved it to another class, and it looks neat and clean now)
这篇关于静态类的C#MEF用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!