This project has moved. For the latest updates, please go here.

Service Locator and MEF

Dec 14, 2010 at 9:32 AM



I am a newbie in MEF/DI jargon, so please pardon my stupid question:)

I am using MEF for my composite application, for injecting dependencies, I am using attributes such as Export and ImportingConstructor etc.

But all this is done as part of the constructor, i.e. while creating a Object like


Public Myclass (IMyservice myservice) {

// do something


Now I want to perform something of this sort,

SomeService.ShowDetails(<Get me a concrete implementation of IMyservice>).

Is this possible? I am trying create concrete implementation of IMyservice inside a function!

How does MEF performs a Service location? Do we need to use any separate Service locator (aka Common service locator) for achieving the same?


Dec 16, 2010 at 12:36 PM
Edited Dec 16, 2010 at 12:37 PM

Based your explanation I understand that you have more tha one implementation of IMyService and you want to inject one of the implementations. You can do this

[Export("MyClass1 ", typeof(IMyService)]
public class MyClass1 : IMyService

[Export("MyClass2 ", typeof(IMyService)]
public class MyClass2 : IMyService

And when you want to inject MyClass1 in your constructor do this

public Test([Import("MyClass1")] IMyService myService)

SO you now have the implementation you need. I hope I understood your question correctly.