Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MEF: What if I have multiple exports but need only one import?

Tags:

c#

.net

mef

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.

like image 495
Venemo Avatar asked Dec 09 '09 19:12

Venemo


2 Answers

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.
like image 36
Reed Copsey Avatar answered Nov 17 '22 16:11

Reed Copsey


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.

like image 72
Daniel Plaisted Avatar answered Nov 17 '22 17:11

Daniel Plaisted