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
3: private readonly IKernel _kernel;
5: public NinjectDependencyResolver(IKernel kernel)
7: _kernel = kernel;
10: public object GetService(Type serviceType)
12: return _kernel.TryGet(serviceType);
15: public IEnumerable<object> GetServices(Type serviceType)
17: return _kernel.GetAll(serviceType);
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:
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):
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!