使用 MEF 满足现有对象的导入
给定一个带有 [Import] 标签的任意已存在的对象,为了让 MEF 填充导入,我必须做什么手鼓舞?
许多博客文档似乎是针对 MEF 预览版本构建的,并且不再起作用 - 我正在使用属于 .NET 4.0 一部分的已发布文档(或者 MEF 2.0 Preview 3)。
AggregateCatalog _catalog;
CompositionContainer _container;
public void Composify(object existingObjectWithImportTags)
{
lock(_container) {
var batch = new CompositionBatch();
// What do I do now?!?!
}
}
Given an arbitrary already existing object which is attributed with [Import] tags, what's the tambourine dance I have to do in order to get MEF to fill in the imports?
Much of the blog documentation seems to be built against preview versions of MEF and don't work anymore - I'm using the released one that's part of .NET 4.0 (or alternatively, MEF 2.0 Preview 3).
AggregateCatalog _catalog;
CompositionContainer _container;
public void Composify(object existingObjectWithImportTags)
{
lock(_container) {
var batch = new CompositionBatch();
// What do I do now?!?!
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MEF 从目录中注册的已注册程序集(包括当前程序集)中的导出类型解析导入(通过属性或构造函数注入)以及它们自己的依赖项。
如果您想直接创建对象(使用
new
关键字),或者创建时导出尚未准备好,您可以使用容器为了满足对象的导入,使用:我已经整理了一个小场景来做到这一点。代码如下:
现在,只需使用
new Tests(new CompositionContainer()).Test();
即可启动演示。希望这有帮助:)
MEF resolves Imports (through property or constructor injection), along whith their own dependencies, from exported types in the registered assemblies registered in the catalog (including the current assembly).
If you want to create an object directly (using the
new
keyword), or in case the export wasn't ready at the time of the creation, you can use the container to satisfy the imports of an object, using:I've put together a little scenario doing just that. here's the code:
Now, just use
new Tests(new CompositionContainer()).Test();
to start the demo.Hope this helps :)
ComposeParts 是您正在寻找的扩展方法。
它只是创建一个 CompositionBatch 并调用 AddPart(AttributedModelServices.CreatePart(attributedObject)),然后调用 _container.Compose(batch)。
ComposeParts is an extension method that you are looking for.
It simply creates a CompositionBatch and calls AddPart(AttributedModelServices.CreatePart(attributedObject)) and then calls _container.Compose(batch).