使用静态类的C#MEF用法

noa*_*AVE 12 .net c# mef c#-4.0

我的解决方案中有一个静态类,用于处理各种程序集.我想通过MEF链接它们,所以我在课堂上创建了一个字段.

[Import(typeof(A))]
    static private A _a1;
Run Code Online (Sandbox Code Playgroud)

然后我有一个方法,我将程序集名称作为参数传递:

    public static A LoadPackage(string filePath)
    {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(filePath));
            var _container = new CompositionContainer(catalog);
            ???
    }
Run Code Online (Sandbox Code Playgroud)

那么有没有办法从filepath指定的程序集中导入类型?

我做不到:

_container.ComposeParts(this);
Run Code Online (Sandbox Code Playgroud)

因为类是静态的,我也不能这样做

_container.ComposeParts(_a1);
Run Code Online (Sandbox Code Playgroud)

(开头可能完全错误)因为A没有任何构造函数(所以_a1为null)

Wim*_*nen 12

MEF旨在为您创建和初始化对象.它不处理静态类中的状态.

我建议您将类及其字段设置为非静态,[PartCreationPolicy(CreationPolicy.Shared)]如果要强制执行单例行为,请将其标记为.

另请参阅关于MEF和单例模式的其他问题.


noa*_*AVE 11

事实证明,我正在寻找的方法是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>();
}
Run Code Online (Sandbox Code Playgroud)

我把我的田地填满了(以防万一,我已经将它移到了另一个班级,现在看起来整洁干净)