静态类的C#MEF用法 [英] C# MEF usage with static classes

查看:81
本文介绍了静态类的C#MEF用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的解决方案中有一个静态类,该类用于处理各种程序集.我想通过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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆