使用 MEF 进行 DI/IoC 的资源和示例
我进行了大量搜索并寻找有关使用 MEF 进行 DI 的示例。 我知道它不是 DI,但从我听到的(真正在播客中听到的)来看,它可以这样使用……但我找不到任何博客文章或示例。
我已经在这个项目中使用 MEF(以支持插件),并且认为利用 DI 也很好。
也许我找错了树?
I've searched high and look for samples about using MEF for DI. I know its not DI but from what I hear (really hear in podcasts) it can be used as such...but I can't find any blog posts or samples.
I am using MEF in this project already (to support plugins) and thought it would be nice to leverage for DI also.
Maybe I am barking up the wrong tree?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可以通过一个例子来描述。 例如,假设您有一个核心库,所有定制应用程序都基于该库。 将其命名为 MyCompany.Core。 通常,您编写的每个应用程序都必须包含对 MyCompany.Core 的引用,然后应用程序必须负责引导并调用 MyCompany.Core 以启动相应的服务等。正确的顺序。 当您考虑到核心本身可能更好地知道它应该如何启动等时,这没有多大意义。
要使用 MEF 进行依赖项注入,您的核心将这样做:
核心本身将包含应用程序启动代码,一旦启动了所有服务,可能会调用类似的内容:
在定制应用程序中,您必须导出自己:
现在定制应用程序可以包含对 MyCompany.Core 的直接引用,并且可以直接调用服务,或者您可以甚至将服务公开为导出并将它们导入到应用程序中。 例如,在核心中:
然后在定制应用程序中:
...当您想要使用它时:
据我从文献中可以看出,这就是依赖注入的本质。
This can be described by an example. For instance, let's say you have a core library that you base all your bespoke applications on. Call it MyCompany.Core. Normally, every application you write has to contain a reference to MyCompany.Core, and then the application has to take care of bootstrapping and calling into MyCompany.Core to start the appropriate services, etc., in the correct order. This doesn't make much sense when you consider that the core itself probably knows better how it's supposed to be started up, etc.
To use MEF for dependency injection, your core would do this:
The core itself would contain the application startup code, and might call something like this once it had started up all of its services:
In the bespoke application, you have to export yourself:
Now the bespoke application could contain a direct reference to MyCompany.Core, and could call services directly, or you could even expose the services as Exports and Import them into the application. For instance, in the core:
Then in the bespoke application:
...and when you want to use it:
As far as I can tell from the literature, that's the essence of dependency injection.