One of the comment posted in my earlier example of MEF was what if we have two implementations of the same interface and we need to decide at run time which implementation to use.
This is where ‘ExportMetadata’ comes to the rescue. The idea here is the implementer can expose any number of metadata properties which can be anything from simple primitive data types to complex class structure. Now when we do the import we get access to these metadata which we can read and decide which implementation to use.
Lets take an example of a Car interface called ‘ICar’. This interface has two methods called ‘GetBrand’ and ‘GetWeight’. Now anyone implementing this interface will expose a metadata called ‘Type’ (e.g. SUV, Sedan etc…) which consumer can use to filter the result after importing the definition.
We will keep the project structure similar (source code uploaded along with the blog post) and also in this example we will keep the composition logic to a separate class to keep the Main function simple.
So our interface ‘ICar’ looks something like this.
Now lets look at the implementation part, first Impl1 (notice the ExportMetadata tag):
Ok, so we got our interface definition and two implementation and we said earlier in this post that we will keep our main function clean. So why not have a separate helper class which will do the composition work for us and return the result based on the criteria specified.
Now this helper class can be placed anywhere you need, but for simplicity I have put into the ConsolApp project itself. By the way the Solution structure is exactly same what we used in example one. Only thing I have added is ‘ConsolApp1’ to demonstrate the ‘ExportMetadata’ functionality.
Coming back to the helper class which does the composition and returns the filtered list of implementation based on the criteria specified for ‘Type’ (ExportMetadata tag specified for implementation), ,you will notice the ’CarFactory’ class in the ConsolApp1.
This makes our Main function in ConsolApp1 pretty simple.
Everything else will remain pretty much same e.g. Extension folder and copying and pasting the implementation dll’s to the extension folder. Now when we run this example we can see the result.
I hope you will find this information helpful and comments and suggestions are very much appreciated.
*Note: Both the examples of MEF are real time extensible where we can put the implementation dll in the Extension folder while the application is still running and we can see that the application picks up the recently pasted dll in the extension folder without restarting the application, which is very powerful.
Next we will see how we to update the implementation dll while the process is still running which will give very robust infrastructure of update of the functionality.
Sample Code (C#) can be downloaded from: