c# - 带有元数据的 MEF GetExportedValue

标签 c# dependency-injection mef

我想将 MEF 用作我项目的 DI。我有 1 个项目,每个应该组成的类都驻留在那里(它们共享一个接口(interface))。现在我想通过指定元数据值来创建其中之一。以下是定义:

public interface IGatewayResponseReader
{
    object Read(string msg);
}

[Export(typeof(IGatewayResponseReader))]
[ExportMetadata(G3Reader.META_KEY, "value1")]
public class TestReader1 : IGatewayResponseReader
{
    ...
}

[Export(typeof(IGatewayResponseReader))]
[ExportMetadata(G3Reader.META_KEY, "value2")]
public class TestReader2 : IGatewayResponseReader
{
    ...
}

现在我想通过MEF创建一个TestReader1的实例,但是我不知道如何通过CompositionContainer按元数据进行过滤。我想要类似的东西

Container.GetExportedValue<IGatewayResponseReader>();

但要指定元数据来选择创建哪个类实例。

非常感谢您的帮助。

谢谢。

最佳答案

@Dmitry Ornatsky 提供的答案是正确的,但提供导出元数据的首选方法是使用自定义导出属性使用强类型元数据:

public interface IGatewayResponseReaderMetadata
{
    string Key { get; }
}

[MetadataAttribute]
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Property )]
public class GatewayResponseReaderExportAttribute : ExportAttribute
{
    public GatewayResponseReaderExportAttribute( string key )
        : base( typeof( IGatewayResponseReader ) )
    {
        this.Key = key;
    }

    public string Key { get; set; }
}

[GatewayResponseReaderExport("value1")]
public class TestReader1 : IGatewayResponseReader
{
}

然后可以使查找导入的代码成为类型安全的。请注意,在访问 Value 属性之前检查 import 是否不为 null 是个好主意:

class Program
{
    [ImportMany]
    private List<Lazy<IGatewayResponseReader, IGatewayResponseReaderMetadata>> _readers;

    static void Main( string[] args )
    {
        CompositionContainer container = new CompositionContainer( new AssemblyCatalog( Assembly.GetExecutingAssembly() ) );

        Program program = new Program();
        container.SatisfyImportsOnce( program );


        var reader = program._readers.FirstOrDefault( r => r.Metadata.Key == "value1" );
        if ( reader != null )
            reader.Value.Read( ... );
    }
}

关于c# - 带有元数据的 MEF GetExportedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7204067/

相关文章:

C# 根据其他属性值自动分配属性

java - 使用Guice : No implementation bounded

c# - .NET Core 在另一个单例服务中注入(inject)单例服务

asp.net - 依赖注入(inject)和代码可维护性

.net-3.5 - 使用MEF + MVVM照明工具包时组成零件的理想场所?

c# - 从另一个局部 View 更新局部 View - ASP.NET MVC2

c# - 在标签名称中使用变量

c# - 如何在未安装 Visual Studio 的计算机上安装 Windows 服务?

c# - MEF 通用进口

asp.net - 在 MVC 中使用 MEF 实现可插拔架构