I recently added MEF to an MVC/WebAPI application using a variety of resources including this SO answer How to integrate MEF with ASP.NET MVC 4 and ASP.NET Web API. While this worked for a time, I started to receive intermittent errors related to making connections to the database, the most frequent one being: "System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached."
I realized I was leaking connections but didn't understand why. All of my repositories implemented IDisposable and disposed of their connections when done. Putting breakpoints in my dispose methods quickly revealed that they were never being hit. When I based my code off of the example linked to above, I noticed the lack of any cleanup, but being new to MEF and MVC I wrongly assumed that cleanup was being done somewhere in MVC's/MEF's dependency pipeline.
I'm wondering how other people have tackled using MEF to properly scope composition on a per request basis in both MVC and WebAPI?
I have found vague guidance here and there and it's all geared toward either MVC or WebAPI. Mef.codeplex has an almost complete MVC centric solution here: https://mef.codeplex.com/releases/view/79090 but it's based off of a preview version of MVC. I found a WebAPI solution here: https://github.com/WebApiContrib/WebApiContrib.IoC.Mef. I'm rolling my own solution at the moment but as I hate to reinvent the wheel, I thought I'd ask to see if anyone knew of one rolling around already.
I ended up tackling this problem myself over the holidays after not finding anything to my satisfaction. MEF contrib on CodePlex had a good start but it was unfinished. I incorporated it with a few modification and combined that with some research and trial and error.
I've created a project on Github (link below, I know external links are frowned upon but it's just too much code to include inline). In it are four projects. The first provides core composition and teardown, the two libraries put the core into the context of MVC and WebAPI respectively, and the last is just a quick sample MVC app with two controllers that each depend on another class which is injected. One caveat, I consider the WebAPI project unfinished as it doesn't yet include facilities for WebAPI filter providers (and maybe other things I haven't thought of or needed yet).
I hope this helps.
https://github.com/rlvandaveer/Heliar-Web-Composition