воскресенье, 25 декабря 2011 г.

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:

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

RegisterDIContainer();

AreaRegisteration.RegisterAllAreas();

RegisterRoutes(RouteTable.Routes);

}

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);
}


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

var controllers = ServiceLocator.Current
.GetAllInstances();

Code on…

Комментариев нет: