Using MEF with Common Service Locator

“The Managed Extensibility Framework (MEF) simplifies the creation of extensible applications. MEF offers discovery and composition abilities that you can leverage to load application extensions.” – (

“The common service locator library contains a shared interface for service location which application and framework developers can reference”  – (


How to get them both working together, is as below.

NOTE: I am assuming that the reader is aware of Dependency Injection pattern & the Common Service Locator.

The Steps:

  1. Download the file & extract the MefServiceLocator class written by Glen Block
  2. Create a new ASP.Net MVC 2.0 Web Application Project
  3. Include the MefServiceLocator class into this project
  4. Open the Global.asax.cs file
  5. Make the following code change in the Application_Start event:
    protected void Application_Start(){     

  6. Write the RegisterDIContainer method as:
    protected void RegisterDIContainer(){
        var catalog = new AggregateCatalog(     
            new AssemblyCatalog(Assembly.GetExecutingAssembly()),     
            new DirectoryCatalog(Server.MapPath(“~/Plugins”))
        var composition = new CompositionContainer(catalog); 
        var mef = new MefServiceLocator(composition);
        ServiceLocator.SetLocatorProvider(() => mef);


  7. With this in place, you are now good to do:  

    var controllers = ServiceLocator.Current

Code on…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s