Ninject and ChildKernel in MVC3 project: “Error lo

2019-09-14 23:51发布

问题:

I'm using Ninject (3.0) in my ASP.Net MVC3 project. At some point of request handling I want to execute some tasks.

I'm using session-per-request pattern but don't want these tasks to share the same Session as current Request has. So, I thought, ChildKernels could help me with this issue. I was going to create another binding for ISession in child kernel, but started with that:

var child = new Ninject.Extensions.ChildKernel.ChildKernel(NinjectMVC3.Kernel);
child.Dispose();

If I execute the code like that during request I get Error loading Ninject component ICache exception at the end of my request (not at .Dispose() call). If I remove child.Dispose() everything is fine.

So, am I choosing the right way to go with ChildKernel? Is it safe to use the child kernels without explicitly disposing them? Why Ninject throws at the request end if I dispose the child kernel?

回答1:

The exception is thrown because you load all the modules from the extensions into the child kernel. Creating the kernel with LoadExtensions=false would fix that problem. But this is not the solution in your case.

The intention of the ChildKernel isn't really for different scoping. You would need to register everything for the tasks on that child kernel. Just the session won't be enough. Adding just a conditional binding for the session is far the better option.