Search code examples
asp.netasp.net-mvc-2dependency-injectionmef

The best way to import a collection of values in a controller using MEF


I have an ASP.NET MVC2 application that supports visualization plug-ins/providers. The IVisualization interface is defined in a common assembly which is referenced by both the ASP.NET MVC2 app, and any visualization providers.

In the Visualization controller, I have a method which returns all the applicable visualizations for a given set of data. In order to scan the available providers, I use the following code in the controller's ActionMethod.

var catalog = new DirectoryCatalog(HttpRuntime.BinDirectory); 
var container = new CompositionContainer(catalog);
var visualizations = container.GetExportedValues<IVisualization>();

However, I feel like if I have the following in the controller

[ImportMany]
public IEnumerable<IVisualization> Visualizations { get; set; }

then the import should happen automatically. What am I missing that prevents the automatic imports?

Also, is the code that I am currently using going to kill scaling of website?

Thanks, Erick


Solution

  • If you have a controller that declares that particular property import, you must programatically call one of MEF's methods to satisfy them.

    Some options are:

    container.GetExportedValues<MyController();
    container.ComposeParts(controllerInstance);
    

    among others.

    I hope this illustrates my point.