views:

783

answers:

4

I've searched high and look for samples about using MEF for DI. I know its not DI but from what I hear (really hear in podcasts) it can be used as such...but I can't find any blog posts or samples.

I am using MEF in this project already (to support plugins) and thought it would be nice to leverage for DI also.

Maybe I am barking up the wrong tree?

A: 

Another similar thread that has information about this topic :-)
http://stackoverflow.com/questions/108116/mef-vs-ioc-di

Joel Martinez
I want to know the similarities..not the differences. I hope to use MEF for DI.
Detroitpro
+1  A: 

This can be described by an example. For instance, let's say you have a core library that you base all your bespoke applications on. Call it MyCompany.Core. Normally, every application you write has to contain a reference to MyCompany.Core, and then the application has to take care of bootstrapping and calling into MyCompany.Core to start the appropriate services, etc., in the correct order. This doesn't make much sense when you consider that the core itself probably knows better how it's supposed to be started up, etc.

To use MEF for dependency injection, your core would do this:

[Import("/Application", typeof(IBespokeApplication))]
private IBespokeApplication bespokeApplication;

The core itself would contain the application startup code, and might call something like this once it had started up all of its services:

bespokeApplication.Start();

In the bespoke application, you have to export yourself:

[Export("/Application", typeof(IBespokeApplication))]
public class MyApplication : IBespokeApplication
{
    public void Start()
    {
        /* start app */
    }
}

Now the bespoke application could contain a direct reference to MyCompany.Core, and could call services directly, or you could even expose the services as Exports and Import them into the application. For instance, in the core:

[Export("/LoggingService", typeof(ILoggingService))]
public class NLogLoggingService : ILoggingService
{
    /* ... */
}

Then in the bespoke application:

[Import("/LoggingService", typeof(ILoggingService))]
private ILoggingService loggingService;

...and when you want to use it:

loggingService.LogInformation("My Message");

As far as I can tell from the literature, that's the essence of dependency injection.

Scott Whitlock
A: 

You might have a look at the WPF Application Framework (WAF) which provides sample applications that are using the Model-View-ViewModel pattern together with MEF as an IoC Container.

jbe
A: 

Check this article as well: http://codebetter.com/blogs/glenn.block/archive/2009/08/16/should-i-use-mef-for-my-general-ioc-needs.aspx

It touches on both the differences and similarities, though more heavy on the differences.

Glenn

Glenn Block