13

I'm trying to wrap my mind around MEF. There is one thing I don't understand.

Assume that I have an interface, named ISomething, which is a contract, and I have more than one assemblies in a folder that contains my application, and I have no idea how many ISomething implementations are in them, or which one contains one.

If I create a host application in which I use MEF, and would like to get an ISomething, but only one, how does MEF decide which implementation it will give me?

Or, similarly to a common IoC container, how do I tell it which implementation should it use?

Thanks in advance for your answers.

Venemo
  • 18,515
  • 13
  • 84
  • 125

2 Answers2

14

See this blog post for a discussion of this issue and some of the options you have. Also, Glenn Block has a blog post describing how to customize the container behavior with defaults.

Daniel Plaisted
  • 16,674
  • 4
  • 44
  • 56
  • 1
    Glenn's post about ExportProviders just gave me a good idea. Perhaps I should make an ExportProvider that accepts some sort of configuration in which the default export can be specified. – Venemo Dec 09 '09 at 21:30
  • 1
    That is perfectly resonable, and it was one of the scenarios we considered. – Glenn Block Dec 10 '09 at 10:13
11

In the case of MEF, if you have many Exports that will satisfy an Import, you have two options:

  1. Change your Import around to use [ImportMany]. Decide, at runtime, which of the Imports to use for your contract, potentially just picking the first, or one at random.
  2. Use [ImportMany] in conjunction with Metadata in order to decide which Import to use.
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • This is a good idea, however, I would prefer to do something like in Windsor, to specify a concrete implementation from configuration, and tell MEF to use that. – Venemo Dec 09 '09 at 19:20
  • @Venemo: You should be able to do that, using the metadata at runtime. – Scott Whitlock Jan 19 '10 at 13:22