Hello,
I have just spent couple of hours trying to do some MVC4 + MEF2 (with parts defined in separate assembly), also agree with cmschick, lot of samples but there are not 2 working the same... and none of them working as expected with the environment I have.
Anyway I finally managed to have it working as expected, and here are my findings, just in case these could help someone.
Here is my setup:
I have a simple ASP MVC 4 web application, and I want to separate some functionality into a separate assembly with the scope of reusing them in other projects (e.g. security infrastructure and access control at very granular level - buttons...fields and so on). I would use RazorGenerator in the external assembly to precompile the views.
The only configuration that worked properly for me and my use case is as following:
- I had to uninstall what I installed from NuGet because I got an error "Ambiguous....." every time I wanted to put the external assembly into the catalog, eventually I tracked the problem to the generated class of the view with RazorGenerator tool, I don't understood why that class would affect the composition it was not in a Part folder it was not tagged with Export attribute.
But then I observed that the binaries from NuGet had version 1.0.0.0 and the binaries that I obtained by compiling source code from CodePlex were 1.1.0.0 so I decided to uninstall the NuGet and use the binaries I had compiled.
With these binaries I had to use a different approach to configure the composition actually a pretty simple one:
publicstaticclassCompositionConfig
{
publicstaticvoidRegisterComposition()
{
var
a = newAssembly[] { typeof(CompositionConfig).Assembly,typeof(IAuthService).Assembly
};
CompositionProvider.AddPartsAssemblies(a);
}
This way the composition container is properly set and I had no errors, the parts exported from the other assembly get injected properly also the precompiled Razor views works.
There is no need to create a custom controller factory, in the past I follow such an approach - I mean custom controller factory - (with MEF 1) but for some reasons the application was leaking a lot and I changed MEF 1 to an earlier version of MEF 2 (with MVC 3), and I got rid of leaks, so watch out if your parts get collected as expected when you are using custom controller factory.