11
I'm building an MVC 3 application where MEF is used. The main idea is to have plug-in mechanism where models, controllers and views are loaded dynamically during runtime from mef container.
Each plugin/module consists of two assemblies:
- Module1.Data.dll (contains definitions of models)
- Module1.Web.dll (contains controllers and views)
and are put in the Plugins directory inside web application bin:
- WebApp/Bin/Plugins/Module1.Data.dll
- WebApp/Bin/Plugins/Module1.Web.dll
- WebApp/Bin/Plugins/Module2.Data.dll
- WebApp/Bin/Plugins/Module2.Web.dll
- WebApp/Bin/Plugins/ModuleCore.Data.dll
- WebApp/Bin/Plugins/ModuleCore.Web.dll
- etc...
There is also core module that is referenced by all other modules: ModuleCore.Data.dll and respectively ModuleCore.Web.dll.
Then, in Global.asax, container is build in the following way:
AggregateCatalog catalog = new AggregateCatalog();
var binCatalog = new DirectoryCatalog(HttpRuntime.BinDirectory, "Module*.dll");
var pluginsCatalot = new DirectoryCatalog(Path.Combine(HttpRuntime.BinDirectory, "Plugins"), "Module*.dll");
catalog.Catalogs.Add(binCatalog);
catalog.Catalogs.Add(pluginsCatalot);
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);
AppDomain.CurrentDomain.AppendPrivatePath(Path.Combine(HttpRuntime.BinDirectory, "Plugins"));
CustomViewEngine is created and registered and used for finding views in module assembly:
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CustomViewEngine());
controller factory for loading controllers from container:
ControllerBuilder.Current.SetControllerFactory(new MefControllerFactory(_container));