OK, what you need to do (without prescribing performance, it's just to see it work)
public class GeneralController : Controller { [Import] public ITranslator Translator { get; set; } public JsonResult Translate(string text) { var container = new CompositionContainer( new DirectoryCatalog(Path.Combine(HttpRuntime.BinDirectory, "Plugins"))); CompositionBatch compositionBatch = new CompositionBatch(); compositionBatch.AddPart(this); Container.Compose(compositionBatch); return Json(new { source = text, translation = Translator.Translate(text) }); } }
I am not an expert in MEF, and frankly, I use it for me, it does not do much for me, since I use it only for loading a DLL, and then I have a dependency entry point, and then I use DI containers , not MEF.
MEF is a must - as far as I have seen. In your case, you need to proactively compose what you need to be MEFed, i.e. Your controller. So, your factory controller should make up your instance of your controller.
Since I rarely use MEFed components in my MVC application, I have a filter for those actions that require MEF (instead of MEFing all my controllers in my controller):
public class InitialisePluginsAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { CompositionBatch compositionBatch = new CompositionBatch(); compositionBatch.AddPart(filterContext.Controller); UniversalCompositionContainer.Current.Container.Compose( compositionBatch); base.OnActionExecuting(filterContext); } }
Here UniversalCompositionContainer.Current.Container is a singleton container initialized by directory directories.
My personal view on MEF
MEF, not the DI framework, it does a lot. So there is a lot of overlap with DI and , if you are already using DI frameworks, they should collide .
MEF is very effective at loading DLLs at runtime, especially when you have a WPF application where you can load / unload plugins and expect everything else to work as it did by adding / removing functions.
For a web application, this does not make much sense, since you really should not throw DLLs into a working web application. Consequently, its use is very limited.
I am going to write a post about plugins in ASP.NET MVC and update this post with a link.