I'm using Ninject.MVC3 with WebAPI.
Originally, I was using the implementation of NinjectResolver and NinjectScope as outlined here,i.e. using _kernel.BeginBlock()
,
I noticed that BeginBlock() gets invoked on each call to the Controller. On load testing the controller (over several hundred invocations) I noticed that the memory consumption of w3wp increased significantly (upwards of 1.4 gigs on high load) and the GC would never reclaim any memory.
Per this SO post, the kernel should not be disposed and BeginBlock() should not be used. Following which I updated the Resolver and Scope like so:
public class NinjectScope : IDependencyScope
{
protected IResolutionRoot resolutionRoot;
public NinjectScope(IResolutionRoot kernel)
{
resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).SingleOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).ToList();
}
public void Dispose()
{
//Don't dispose the kernel
//IDisposable disposable = (IDisposable)resolutionRoot;
//if (disposable != null) disposable.Dispose();
//resolutionRoot = null;
}
}
public class NinjectResolver : NinjectScope, IDependencyResolver
{
private IKernel _kernel;
public NinjectResolver(IKernel kernel): base(kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectScope(_kernel);
//what's the difference between using just _kernel vs _kernel.BeginBlock()
//return new NinjectScope(_kernel.BeginBlock());
}
}
The memory consumption lowered significantly following this change(i.e. using the above implementation). I would like to understand why this is. What is it that BeginBlock() really does and when should one use it.
Is the above implementation accurate?