使用C#MEF将其他属性导入元数据

时间:2014-08-10 14:08:59

标签: c# mef

在网上使用一些教程,我使用C#中的MEF为我的需求创建了一个元数据类

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public class ActionMetadataAttribute : Attribute
{
    public bool HasSettingsDialog { get; set; }
    public bool UseThreadedProcessing { get; set; }
}

public interface IActionMetadata
{
    [DefaultValue(false)]
    bool HasSettingsDialog { get; }

    [DefaultValue(false)]
    bool UseThreadedProcessing { get; }
}

我有不同类型的插件类型,所以有e。 G。 IHandlerMetadataHandlerMetadataAttribute。现在我通过Lazy帮助程序加载它以允许严格键入的元数据。

[ImportMany(typeof(IActionPlugin))]
private IEnumerable<Lazy<IActionPlugin, IActionMetadata>> _plugins = null;

public ActionManager()
{
    var catalog = new DirectoryCatalog(".");
    var container = new CompositionContainer(catalog);
    container.ComposeParts(this);

    foreach (var contract in _plugins)
    {
        Debug.WriteLine(contract.Metadata.HasSettingsDialog);
    }
}

完美无缺。现在,我也想了解一些有关插件的信息。所以我创建了PluginInformationAttribute

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public class PluginInformationAttribute : Attribute
{
    public string Name { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string Url { get; set; }
    public string Contact { get; set; }
    public string Description { get; set; }
    public Version Version { get; set; }
}

现在的问题是:如何在上面的代码片段中的for循环中访问此属性?有什么办法或我的设计错了吗?我不想将PluginInformation内容添加到IActionMetadata,因为我想在不同类型的插件上使用它,例如: G。在IHandlerMetadata

1 个答案:

答案 0 :(得分:1)

如果指定导出类的类型作为ActionMetadataAttribute的属性,则可以通过GetCustomAttributes方法反射访问该类的每个属性

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public class ActionMetadataAttribute : Attribute
{
    public bool HasSettingsDialog { get; set; }
    public bool UseThreadedProcessing { get; set; }
    public Type ClassType { get; set; }
}

var attributes = contract.Metadata.ClassType.GetCustomAttributes(typeof(PluginInformationAttribute), true)
相关问题