Search code examples
c#.netmef

Create a Factory with MEF


I basically have a class that has a factory method that takes in a type of Product we have and returns an implementation of IProfileService specifically able to handle that product. If I wanted to use MEF so that I could Implement the different implementations of the IProfileService in another DLL that will only get installed when that particular product gets installed what would be a good approach?

My first thought was an ImportMany with MetaData to describe what product it handles and then just use a LINQ query in my factory method to compare the passed in product to the MetaData. Does this sound good or is there a better way?


Solution

  • I think that approach is will work just fine. I can't think of another way that would be better.

    A technique that could be used with this approach is Lazy loading. See this great article on MEF. By using Lazy<T> in your exports, your IProfileService objects won't be created until you need them.