C# ServiceLocator GetAllInstances不包含指定了约定名称的实例

C# ServiceLocator GetAllInstances不包含指定了约定名称的实例,c#,mef,service-locator,common-service-locator,C#,Mef,Service Locator,Common Service Locator,假设我有一个接口ITest: public interface ITest { void PrintMachineInfo(); } var foo = ServiceLocator.Current.GetAllInstances<ITest>(); foreach (var test in foo) { test.PrintMachineInfo(); } 加上两个实现: [Export("MachineName", typeof(ITest))] [PartC

假设我有一个接口
ITest

public interface ITest
{
    void PrintMachineInfo();
}
var foo = ServiceLocator.Current.GetAllInstances<ITest>();
foreach (var test in foo)
{
    test.PrintMachineInfo();
}
加上两个实现:

[Export("MachineName", typeof(ITest))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class Test1 : ITest
{
    public void PrintMachineInfo()
    {
        Console.WriteLine(Environment.MachineName);
    }
}

[Export(typeof(ITest))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class Test2 : ITest
{
    public void PrintMachineInfo()
    {
        Console.WriteLine(Environment.OSVersion);
    }
}
然后,我尝试检索
ITest
的所有实例:

public interface ITest
{
    void PrintMachineInfo();
}
var foo = ServiceLocator.Current.GetAllInstances<ITest>();
foreach (var test in foo)
{
    test.PrintMachineInfo();
}
var foo=ServiceLocator.Current.GetAllInstances();
foreach(foo中的var测试)
{
test.PrintMachineInfo();
}
结果表明,只能返回
Test2
的实例。由于合同名称的原因,它无法找到
Test1
的实例

我使用MEF++运行所有这些东西。从我的调试中,MefAdapter覆盖了
ServiceLocatorImplBase
中的方法
DoGetAlliances(类型serviceType)
,但它只提供了一个参数
serviceType


那么,如何使用ServiceLocator获取
ITest
的所有实例,而不管该实现是否导出了联系人姓名?

使用Prism提供的
IServiceLocator
的当前实现不可能达到您想要的效果

该实现中被重写的
doGetAlliances()
方法调用
GetExport()方法的最后一个重载:

this.compositionContainer.GetExports(serviceType, null, null);
根据,第三个论点是

contractName:要返回的惰性对象的协定名称,或使用默认协定名称的null或空字符串(“”)

正如您在本主题的备注中所看到的:

默认合同名称是调用GetContractName的结果 方法的类型

默认合同名称基于完整的类型名称,没有任何附加键。这就是为什么您只得到第二个导出:它具有默认的合同名称

因此,如果不确切了解所有合同密钥,就无法通过这种方式获得所有出口

要提供多个导出,同时能够区分它们,可以为每个导出提供附加元数据,并保留相同的导出合同名称:

[Export(typeof(ITest))]
[ExportMetadata("Type", "MachineName")]
public class Test1 : ITest { }

[Export(typeof(ITest))]
[ExportMetadata("Type", string.Empty)]
public class Test2 : ITest { }