繁体   English   中英

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

[英]Importing other attributes to metadata using C# MEF

使用Web上的一些教程,我使用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; }
}

我有不同类型的插件类型,因此有例如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因为我想在不同类型的插件上使用它,例如在IHandlerMetadata

如果将导出类的类型指定为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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM