MVC4 Quick Tip #2–Use Delegates to setup the Dependency Resolver instead of creating a Dependency Resolver class

by ely February 20, 2012 15:29

I’m a big fan of cutting out unneeded or unnecessary code, so here is a tip that isn’t new in MVC4, but I just discovered it and thought it was really cool and worth sharing.  When using IOC in MVC, you setup a class that implements IDependencyResolver, which has methods to return services for a given type.  While these classes where simple, it always seemed like a bit of ceremony was required whenever starting up a new MVC app.

The following example shows what a DependencyResolver class looks like using my favorite IOC framework, Ninject:

   1:  public class NinjectDependencyResolver : IDependencyResolver
   2:      {
   3:          private readonly IKernel _kernel;
   4:   
   5:          public NinjectDependencyResolver(IKernel kernel)
   6:          {
   7:              _kernel = kernel;
   8:          }
   9:   
  10:          public object GetService(Type serviceType)
  11:          {
  12:              return _kernel.TryGet(serviceType);
  13:          }
  14:   
  15:          public IEnumerable<object> GetServices(Type serviceType)
  16:          {
  17:              return _kernel.GetAll(serviceType);
  18:          }
  19:      }

Nothing terribly complicated, but a lot of fluff.

I saw in a demo in last week’s C4MVC talk, that the DependencyResolver that was setup to create the APIController classes had some overrides I never saw before, and low and behold, the standard MVC DependencyResolver also has these overrides:

ioc

So instead of providing the SetResolver method with a DependencyResolver class, you can just provide it two delegate methods that would normally be in the DependencyResolver (GetService, and GetServices):

   1:  DependencyResolver.SetResolver(
   2:                  x => kernel.TryGet(x),
   3:                  x => kernel.GetAll(x));

POW!  Cut that 20+ line class down to a method that takes two parameters.  BAM!

Tags:

mvc

blog comments powered by Disqus

Powered by BlogEngine.NET 2.0.0.36
Theme by Mads Kristensen | Modified by Mooglegiant

About me

@ElyLucas

I am a Denver based software developer, focusing mainly on web technologies in the Microsoft stack.  I dig Asp.Net, MVC, jQuery, C#, JavaScript, and HTML5.  I am starting to dabble in mobile technologies like iOS, Android, and wp7, and have particular interests in mobile web.  I am a Microsoft MVP for Asp.Net/IIS.  I live in Westminster, CO with my wife, son, and dog.  During the day, I sling code for @aspenware creating awesome software.


Month List

Page List

Site hosted by: