通过实现 class 名称获取导出接口

Getting exported interface by implementing class name

我有各种实现特定接口的对象。 在我的代码中的一个地方,我获得了接口的所有导出并将实际的 class 名称保存在数据库中。这是一些快速而肮脏的伪造:

public interface ISomething { }

[Export(typeof(ISomething))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class Something : ISomething { }

[Export(typeof(ISomething))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class SomethingElse : ISomething { }

public class Handler {

    [Import]
    CompositionContainer _container;

    [ImportMany]
    IEnumerable<ISomething> _somethings;

    public void SaveSomething() {
        foreach(ISomething something in _somethings) {
            string className = something.GetType().Fullname;
            SaveToDatabase(className);
        }
    }
}

这很好用,我可以轻松获得所有 ISomething 实现。 但是,稍后我还需要获取特定 class 名称的新实例。

如果我尝试 _container.GetExportedValues<ISomething>,我会得到 SomethingSomethingElse。如果我尝试 _container.GetExportedValue<ISomething>("SomethingElse"),我会收到一个组合错误,指出它找不到任何与约束匹配的导出。

那么,我如何通过只知道 class 的名称来获得 SomethingElse 的新实例?

您必须导出 SomethingElse 显式:

[Export(typeof(SomethingElse))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class SomethingElse : ISomething { }

然后 _container.GetExportedValue<SomethingElse> 起作用。也可以通过给导出命名来导出相同的 class。

[Export("SomethingElse", typeof(ISomething))]

您可以提供两个导出属性,以便您可以按接口名称或自定义名称导入。

像这样:

public interface ISomething { }

[Export(typeof(ISomething))]
[Export("Something", typeof(ISomething))]
public class Something : ISomething { }

[Export(typeof(ISomething))]
[Export("SomethingElse", typeof(ISomething))]
public class SomethingElse : ISomething { }

现在,您可以这样做:

class Test
{
    [ImportMany]
    IEnumerable<ISomething> _somethings;

    [Import("SomethingElse", typeof(ISomething))]
    SomethingElse _somethingElse;
}