【问题标题】:Importing other attributes to metadata using C# MEF使用 C# MEF 将其他属性导入元数据
【发布时间】:2014-08-10 14:08:58
【问题描述】:

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

现在的问题是:我如何才能在上述代码 sn-p 的 for 循环中访问这个属性?有什么办法还是我的设计错了?我不想在IActionMetadata 中包含PluginInformation 的东西,因为我想在不同类型的插件上使用它,例如。 G。在IHandlerMetadata

【问题讨论】:

  • 如果您确实需要此信息作为元数据(即您想在创建实例之前按其属性进行过滤),您必须更改接口(元数据视图)以包含您需要的属性作为元数据访问。
  • 现在就这样做了。虽然我不太喜欢它,但可以正常工作。无论如何,似乎没有其他解决方案。谢谢!

标签: c# mef


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-03
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多