Monday, September 3

ASP MVC 4 with MEF 2 on .NET 4.0

ASP MVC 4 is the latest and greatest of ASP MVC framework.
Even when creating modest web applications there is a need to create well designed software so it will be testable and maintainable.

I've decide to use MEF 2 with ASP MVC 4 in order to inject any dependencies my controller have.
Currently I have only single dependency which is an EventLogger interface I use in several controllers to signal events such as user login, fail to login and other business related events.
Even though it just one dependency I know they will keep on coming so I decide to use MEF and also wanted to use the new registrations API (Convention).

The problem is that after MEF 2 Previous 4 Microsoft decide to change the minimun .NET framework version to 4.5, but my (and most) web hosting only support .NET 4.0.

I've found that I still can use the MEF 2 Preview 4 for now and upgrade as soon as my web hosting will allow to run 4.5 code.

I know it's not the ideal solution but it works and it works good.

I find MEF (Microsoft) and Guice (Google) very a like. The new MEF registration API looks very much like Guice binding API. I know Guice is "just" IoC framework and MEF is much more but for my needs I just need it as IoC for now.

So, just to share some code, when my ASP MVC application starts it invoke this method to setup the composition. This is very very simple but this is the basic on which more parts can be built.



  public class CompositionConfig {
    public static void Init() {
      RegistrationBuilder rb = new RegistrationBuilder();

      SetupParts(rb);

      // Add all controllers
      rb.ForTypesMatching(t => typeof(IController).IsAssignableFrom(t)).Export();

      var ac = new AssemblyCatalog(typeof(CompositionConfig).Assembly, rb);
      CompositionProvider.SetCatalog(ac);
    }

    private static void SetupParts(RegistrationBuilder rb) {
#if DEBUG
      rb.ForType<NoopEventLogger>().Export<EventLogger>();
#else
      rb.ForType<EmailEventLogger>().Export<EventLogger>();      
#endif
    }
  }

No comments:

Post a Comment