2

I am in the process of extending a solution based on MVC 3.

Basically, The solution consists of an MVC 3 project along with some class library projects to manage Business/Data Access.

I'm trying to use MEF to make the application plugin-based. for example, I have a UserManager class in the dll project and I have defined my plugins as follows:

[ImportMany]public List<IUserHooks> Plugins {get; set;}
foreach (var plugin in Plugins)
{
    Plugin.DoTheJob();
}

As you can see, the class is separated from MVC project and controllers. The list is defined my UserManager class.

I know the best approach would be to make UserManager use MEF as well (Probably initialize it in controller's ctor like public MainController(IUserManager UserManager)), But since I just want to add plugin support to the solution, and not writing from scratch, I prefer the fastest shortcut.

How should I define my MEF container object to be able to use it in my class library. Is it necessary to make MVC application using MEF as well? I'd prefer the approach where minimum modification would be necessary to the MVC application.

Kamyar
  • 18,639
  • 9
  • 97
  • 171

1 Answers1

2

MVC3 has baked in support for service location. If you don't want to redefine some of your base classes, but simply want to extend, you could add an instance of a IDependencyResolver that uses MEF. That way you can use that as a base to extend your application. I've written an example on my blog.

Using MVC3's built in architecture allows you to configure your CompositionContainer in your startup and expose it to the rest of the infrastructure.

But, the reality is you probably don't want to be exposing your container in your library. In fact, the only thing you should be doing is simply marking your exports. The reason you can get away with this with MEF is that it is included in the BCL for .NET 4.0. By not coupling your classes to MEF (or infact, coupling your classes to a service locator or inversion-of-control container either), it makes your code more portable, testable and decoupled.

Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
  • Thanks for the answer Matthew. I have tried to test your solution and added a TestDll Project with a simple Import and Export. But the property with "Import" attribute is always null. Is there any additional step I should take to be able to use your framework as a base or I should be just able to reference my dlls with Import/Export and use them? Do you have any idea what I;m doing wrong? Thanks. – Kamyar Apr 23 '12 at 08:23