使用 MEF 在运行时实例化类
我确信这应该很容易,也许我错过了一些明显的东西。我有一堆实现 IClass 接口的类。在运行时,我想使用 MEF DirectoryCatalog 来检索所有实现该 IClass 接口的类的引用。所以,此时我有某种可以实例化的类池。
现在,从现在开始,我希望能够根据当时正在执行的任何业务逻辑来实例化其中一个或多个类。所以我已经设法让 DirectoryCatalog 正常工作。我还设法实现了 ImportMany,以便存在实现 IClass 接口的那些类的集合。
这很好,但我不想简单地拥有所有类的集合,并且我可能希望能够随时实例化该类的多个版本。我开始考虑使用 Lazy,但我认为这只会在实例化类时提供帮助,而不是实例化多少个类。
再一次,我忍不住认为我错过了一些明显的东西。任何帮助将不胜感激。
谢谢
I am sure this should be easy, perhaps I am missing something obvious. I have a bunch of classes that implement the IClass interface. At runtime I want to use the MEF DirectoryCatalog to retrieve references all those classes implementing that IClass interface. So, at this point I have some kind of pool of classes that can be instantiated.
Now, from this point on I want to be able to instantiate one or many of these classes based upon whatever business logic is executing at the time. So I have managed to get the DirectoryCatalog working fine. I have also managed to implement an ImportMany so that a collection of those classes implementing the IClass interface exist.
This would be fine, but I don't want to simply have a collection of all classes and I may want to be able to instantiate more than one version of that class at any time. I started looking at using Lazy, but I assume this would simply assist with when the class is instantiated, not how many.
Again, I can't help but think I am missing something obvious. Any assistance would be most grateful.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MEF不理解你的业务逻辑,因此它不提供仅基于它实例化类的机制并非没有道理。这个想法是,任何向 MEF 公开接口的对象都可以由应用程序用作该角色,包括第三方创建的任何对象。
相反,公开具有接口的工厂,允许它们根据做出决定的任何参数来决定是否实例化对象。如果所有可能的提供者只需要一个对象,请让他们公开一些元数据,这将使客户端能够决定要使用的最佳工厂。
MEF doesn't understand your business logic, so it's not unreasonable that it doesn't provide a mechanism to only instantiate classes based on it. The idea is that any object which exposes an interface to MEF can be used in that role by the application, including any created by third parties.
Instead, expose factories which have an interface that allows them to decide whether or not to instantiate an object based on whatever parameters the decision is made on. If only one object is required from all the possible providers, have them expose some metadata which will enable the client to decide the best factory to use.
我知道已经过去了几年,但进一步的调查帮助我找到了这个解决方案(并且我遇到了与OP完全相同的问题):
如何使用 ExportFactory
总结一下:
然后:
在哪里runner 是我的类,它有一个私有构造函数,可以发挥 MEF 的魔力
希望这对将来的人有帮助
I know it's been a couple of years, but further investigation helped me find this solution (and I had the exact same problem as the OP):
How do you use ExportFactory<T>
And to sum it up:
and then:
where runner is my class with a private constructor that does the MEF magic
Hope this will help someone in the future