ASP.NET MVC + MEF + MefContrib:似乎无法从导出中获取元数据
我使用 asp.net mvc3 和 MEF + MEFContrib 在我的控制器上加载一些服务。发生的情况是我可以加载服务 - IEnumerable
- 使用 [ImportingConstructor]
但当我尝试使用元数据加载服务时 - Lazy
- 我得到一个空的大批。
有什么想法吗?谢谢。
我的代码:
public interface IPluginMetaData
{
string Name { get; }
string Version { get; }
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class PluginMetadataAttribute : ExportAttribute
{
public PluginMetadataAttribute(string name, string version)
: base(typeof(IPluginMetaData))
{
Name = name;
Version = version;
}
public string Name { get; set; }
public string Version { get; set; }
}
[Export(typeof(IPublishService))]
[PluginMetadata("Default", "1.0.0.0")]
public class SamplePublishService : IPublishService
{
}
[ImportingConstructor]
public HomeController(Lazy<IPublishService, IPluginMetaData>[] publisher /* Empty Array */ , IEnumerable<IPublishService> publishers /* Array with 1 service */)
{
}
更新(基于丹尼尔的回答,但仍然没有)
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class PluginMetadataAttribute : ExportAttribute
{
public PluginMetadataAttribute(string name, string version)
: base(typeof(IPublishService))
{
Name = name;
Version = version;
}
public string Name { get; set; }
public string Version { get; set; }
}
[PluginMetadata("Default", "1.0.0.0")]
public class GoogleSampleGroupPublishService : IPublishService
{
}
[ImportingConstructor]
public HomeController([ImportManyAttribute]Lazy<IPublishService, IPluginMetaData>[] publisher)
{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,您需要在构造函数的参数上放置一个 而不是 T 数组。所以尝试将第一个参数更改为
ImportManyAttribute
,因为它们是集合导入。由于其中一个正在工作,我怀疑 MEFContrib 正在做一些事情,这样您就不需要这样做,但它只适用于 IEnumerableIEnumerable>
,或在其前面添加ImportManyAttribute
。我注意到的其他一些问题:您的
PluginMetadataAttribute
派生自ExportAttribute
。这样做的原因是您不必在服务上同时放置导出属性和元数据属性。但是,传递给基类构造函数的类型是导出的协定。所以这应该是IPublishService
而不是IPluginMetadata
。进行更改并从 SamplePublishService 中删除 Export 属性。Normally, you would need to put an
ImportManyAttribute
on the arguments to your constructor, since they are collection imports. Since one of them is working, I suspect that MEFContrib is doing something so that you don't need to do this, but it only works forIEnumerable<T>
and not an array of T. So try changing the first argument toIEnumerable<Lazy<IPublishService, IPluginMetadata>>
, or adding anImportManyAttribute
in front of it.Some other issues I noticed: Your
PluginMetadataAttribute
is derived fromExportAttribute
. The reason you would do that is so that you don't have to put both an export and a metadata attribute on your services. However, the type that you pass to the base class constructor is the exported contract. So this should beIPublishService
instead ofIPluginMetadata
. Make that change and remove the Export attribute from SamplePublishService.