How to discover new MEF parts while the application is running?

后端 未结 1 1344
無奈伤痛
無奈伤痛 2021-01-31 06:03

I\'m using MEF to load plugins in my app. Everything works, but I want new parts to be discovered when they are dropped into my app folder. Is this possible? DirectoryCatalog ha

相关标签:
1条回答
  • 2021-01-31 06:44

    You can use the FileSystemWatcher to detect new DLLs being dropped in your plugin folder. Then you can handle such events by calling DirectoryCatalog.Refresh or AggregateCatalog.Catalogs.Add to update the MEF composition with the new parts.

    Some things to be aware of:

    1. You need to mark your MEF imports as being designed to deal with recomposition, as explained in the MEF programming guide section on Recomposition. Otherwise MEF will raise an error when you try to update them.

    2. FileSystemWatcher raises events on system thread pool threads (unless you make use of the SynchronizingObject property). Be aware that if you call DirectoryCatalog.Refresh from another thread, you must construct the CompositionContainer with the isThreadSafeFlag enabled. You'll also have to think about the thread safety of your property setters that will be called when the composition is updated.

    3. You can also remove catalogs by taking them out of an AggregateCatalog.Catalogs collection. But there is no way to unload the associated assemblies (except by unloading the entire Appdomain). That also means you still can't delete or overwrite an assembly while the application is running.

    0 讨论(0)
提交回复
热议问题