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.” – (mef.codeplex.com)

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

Wow!

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 CommonServiceLocator_MefAdapter.4.0.zip 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(){     
    
        RegisterDIContainer(); 
    
        AreaRegisteration.RegisterAllAreas();     
    
        RegisterRoutes(RouteTable.Routes);
    
    }

  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); 
    
        composition.ComposeParts(this);
    
        var mef = new MefServiceLocator(composition);
    
        ServiceLocator.SetLocatorProvider(() => mef);
    }

     

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

    var controllers = ServiceLocator.Current
            .GetAllInstances<IController>();

Code on…

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s