是否可以将现有实例注入 MEF 插件中?
我们正在创建一个支持使用 MEF 插件的应用程序。我们正在确定用户能够创建什么类型的插件,并希望使用依赖注入为此类插件提供所需的数据。
例如,我们制作一个能够显示列表的插件。为了实现这一点,它需要列表将显示的数据类型的现有 IRepository 实例。
IRepository 是在 datacontext 类中的其他位置创建的,因此我们无法让 MEF 本身创建 IRepository 的实例。
我的想法是通过 importingconstructor 将 IRepository 的现有实例注入到插件中,但是为了实现这一点,我需要让 MEF 知道已经实例化的 IRepository,但我还不知道如何做到这一点。任何帮助将不胜感激。
We are creating an application which supports plugins using MEF. We are determining what type of plugins the user is able to create, and want to use dependency injection to provide this type of plugin with the data it needs.
For example, we make a plugin that is able to display a list. To achieve this, it needs the existing instance of the IRepository for the type of data the list will display.
The IRepository is created somewhere else in a datacontext class, so we are unable to let MEF itself create an instance of the IRepository.
My idea is to inject the existing instance of the IRepository into the plugin via the importingconstructor, however for this to work I need to make the already instantiated IRepository known to MEF, and I haven't been able to figure out how to do it. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法是在容器中组合一个现有值,例如:
但是这只会允许
IRepository
的 1 个实例存在,因为它不给你直接控制所创建的ComposablePart
。如果您想要更细粒度的控制,可以使用CompositionBatch
来达到很好的效果:稍后:
因为我可以访问批处理提供的
ComposablePart
实例,所以我可以稍后将其删除。还有其他方法可以导入无属性部件,通常是通过属性导出:但这当然需要您能够在组合时创建存储库的实例,这可能是也可能不可能。
最后,可以选择使用替代编程模型。 MEF 中的默认(也是最常见)是属性编程模型,您可以利用
[Export]
和[Import]
属性来控制您的组合,但在 MEFContrib 中(以及即将在 MEF2 中推出)能够使用注册编程模型,其中部件基于类似于大多数其他 IoC 容器的机制进行组合。The easiest way is to compose an existing value in the container, e.g.:
But this will only allow 1 instance of the
IRepository
to exist, because it doesn't give you direct control over theComposablePart
that is created. If you want more fine grained control, you can use aCompositionBatch
to great effect:And later on:
Because I have access to the
ComposablePart
instance provided by the batch, I can remove it later on. There are other ways of importing attribute-less parts, generally through property exports:But that of course would require you to be able to create an instance of your repository at composition time, which may or may not be possible.
Lastly, there is the option to use an alternative programming model. The default (and most common) in MEF is the attributed programming model, whereby you utilise
[Export]
and[Import]
attributes to control your composition, but in MEFContrib (and forthcoming in MEF2) is the ability to use a registration programming model whereby parts are composed based on a mechanism similar to most other IoC containers.