简体   繁体   中英

Shared application resources in MEF

In order to dynamically add functionality to an application, I heavily rely on MEF which is a great tool to provide interfaces for third party assemblies (plugins). But now, I not only want a common interface for plugins that I can access from my main application but also offering a interface to the plugins through which they can access various resources (such as objects) from my main application. How could this be done? I'm thinking about something like a plugin API, but I'm not sure if MEF offers such an option.

There are two options that I had in mind for this task:

  • Pass objects as parameters on plugin instantiation

Drawback: If I pass lets say eg a logging object instance which I use elsewhere, a third party plugin could easily call Dispose, making it unusable for the whole application or other plugins. Very dangerous!

  • Declare globally accessible static methods

Instead of constructing your plugins or having static instances somewhere, you might want to use injection...

You can actually inject other objects to your plugin. Most commonly by [ImportingConstructor] .

If you other objects do not implement any MEF exports, you might not be able to use this MEF feature, if this is the case you can also combine eg Unity injection with your MEF plugins so that your Plugins can use the unity container to resolve certain things. This is a little bit tricky but there are certain solutions out there. There is an old but still valid blog post you might want to read: http://pwlodek.blogspot.de/2009/05/unity-mef-integration-layer.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM