[英]C# MEF usage with static classes
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. 我想通过MEF链接它们,所以我在一个类中做了一个字段。
[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? 那么,现在有没有办法从文件路径指定的程序集中导入类型?
I can't do: 我不能:
_container.ComposeParts(this);
since class is `static and neither can I do this 由于课程是静态的,我也不能这样做
_container.ComposeParts(_a1);
(which might be completely wrong to begin with) since A
doesn't have any constructors(so _a1
is null) (一开始可能是完全错误的),因为A
没有任何构造函数(因此_a1
为null)
MEF is designed to create and initialize objects for you. MEF旨在为您创建和初始化对象 。 It doesn't deal with state in static classes. 它不处理静态类中的状态。
I suggest that you make the class and its fields non-static, and mark it with [PartCreationPolicy(CreationPolicy.Shared)]
if you want to enforce singleton behavior. 我建议您将类及其字段[PartCreationPolicy(CreationPolicy.Shared)]
非静态,并如果要强制执行单例行为,则将其标记为[PartCreationPolicy(CreationPolicy.Shared)]
。
See also this other question on MEF and the singleton pattern. 另请参阅关于MEF和单例模式的其他问题 。
Well it turns out that method I was looking for is GetExportedValue
(yeah, I overlooked basic functionality): 好吧,事实证明我正在寻找的方法是GetExportedValue
(是的,我忽略了基本功能):
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) 我的工作就填补了(以防万一,我已经将它移到另一个班级了,现在看起来很整洁)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.