This post is about using MEF (Managed Extensibility Framework) in .NET Core. The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well.
To use MEF first you need to add reference of Microsoft.Composition in your project.json, also you need to import portable-net45+win8+wp8+wpa81. This package is not compatible with the dnxcore50. And here is the project.json file.
I am using the example code from MEF website.
First you need to create interface you want to export. And implement the interface and decorate the class with export attribute.
Now the compose part, Catalogs are not available in Microsoft.Composition namespace.
It will load all the types from the Assembly with export attribute and attach to the import attribute. Here is the complete code.
And here is the screenshot of MEF running on .net core console app.
Update - Loading the plugins from different assemblies
If you have the plugin files available in different assemblies, you can use following code, all the plugin dlls should be in Plugins folder under bin folder.
And your plugin library should reference Microsoft.Composition namespace, which is required to add Export attribute.
Here is the project.json file.
And here is the plugin file.
Happy Programming :)
Did you like this article? Share it with your friends