I have an MVC3 web application where controllers use services to perform certain tasks.
I use to instantiate the needed services in each action separately,like so for example:
public ActionResult Index()
{
ICustomService customService = new CustomService();
var list = customService.ReturnSomething();
.....
return View(list)
}
This was working fine. Then I decided to use MEF for dependecy injection in order to follow better design principles. So now I’m doing something like this:
public class MyController : Controller
{
[Import]
private ICustomService _customService;
public MyController()
{
MEFManager.Compose(this);
}
public ActionResult Index()
{
var list = _customService.ReturnSomething();
return View(list);
}
Where Composition is done by MEFManage.Compose(this) which is the following function:
public static void Compose(object o)
{
var container = new CompositionContainer(
new DirectoryCatalog(Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "bin"))
);
var batch = new CompositionBatch();
batch.AddPart(o);
container.Compose(batch);
}
This actually WORKS but it is 6 to 7 times slower than when I wasn’t using MEF.
Does anyone know why it is so slow? I am doing something wrong?
Spinning up a
CompositionContaineris not a resource intensive task, but, creating aDirectoryCatalogis, it has to scan all available assemblies to identify parts and analyse the composition elements for exports. You could improve this a number of ways:DirectoryCatalog(or preferably aComposablePartCatalog) that all your containers use when constructing, this means that the catalog creation is only done once.IControllerFactoryto spin up your controller instances, or anIDependencyResolverto handle dependency resolution using MVC3’s built in service location mechanism. There are many examples on the web if you search for MEF + MVC.