MEF自定义属性类是否需要ctor(IDictionary<,>)

时间:2012-08-22 22:14:52

标签: c# mef

在.NET 4.0上的MEF中使用自定义属性类时,我得到了CompositionContractMistachException

Unable to create an instance of the Metadata view '(snip).ModuleExportAttribute, (snip), Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because a constructor could not be selected. Ensure that the type implements a constructor which takes an argument of type IDictionary<string, object>.

这是我的ModuleExportAttribute课程,没什么特别的:

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class ModuleExportAttribute : ExportAttribute
{
    public ModuleExportAttribute(string name) : base(typeof(IModule))
    {
        this.Name = name;
    }

    public string Name { get; private set; }
}

用法如下:

[ModuleExport("MyModule")]
public class MyModule : IModule
{ 
   ...
}

添加问题构造函数后,异常消失。

但是,我找不到任何说明此要求的参考。相反,我看到许多示例和博客文章使用自定义属性类而没有这样的构造函数。我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:8)

你是如何尝试导入的?我怀疑这个错误是由你导入类似Lazy<IModule, MetadataExportAttribute>之类的东西引起的,在这种情况下是为了使用具体类型作为元数据类型它必须是一个接口,在这种情况下我们生成一个代理类型或者它必须是采用IDictionary<string,object>的类型,以便可以将元数据传递给它。

尝试类似:

public interface IModuleMetadata
{
  string Name { get; }
}

然后将导入更改为:

[Import]
Lazy<IModule, IModuleMetadata> Module;

我也希望让我的ExportAttribute实现IModuleMetadata接口,以确保它们保持一致,但这并非绝对必要。