I am using Ninject together with MVC3 to inject my controller dependencies. Sometimes I get slow timings in MVC Mini profiler even before the controller actions are executed. Since I don't do much before that time I thought it might be an issue with my usage of Ninject. Is there an existing way to get some timing information from ninject? Perhaps a config option to log how long dependency resolution took or if not what would be a good way to add this myself, is there a class I can extend or wrap?
2 Answers
You can write a decorator for the NinjectDependencyResolver by implementing the IDependencyResolver interface and replace it on the DependencyResolver.
DependencyResolver.SetResolver(new ProfilingResolver(DependencyResolver.Current));
public class ProfilingResolver : IDependencyResolver
{
private readonly IDependencyResolver decoratedResolver;
public ProfilingResolver(IDependencyResolver decoratedResolver)
{
this.decoratedResolver = decoratedResolver;
}
public object GetService(Type serviceType)
{
using (MiniProfiler.Current.Step("Get_" + serviceType.Name))
{
return this.decoratedResolver.GetService(serviceType);
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
using (MiniProfiler.Current.Step("GetAll_" + serviceType.Name))
{
return this.decoratedResolver.GetServices(serviceType);
}
}
}
Firstly, my default answer would be:-
I've never seen DI showing up as a statistically significant percentage of anything interesting in a profile. Go Compose!
(This post started life as a comment:- @olle have you looked at the source? There are a number relatively simple extensions that 'wrap' the resolution process and shouldnt be too complex to grok. Given that you're using the Mini Profiler and it's pretty easy to stuff things into, it'd seem to be a relatively straightforward extension to do. I know this is a PITA response to get on a forum but I personally am thankful for being told to go Use The Source a few years back - the Ninject code base and its tests are a genuine joy to read.)