I am using MVC 3 with Ninject. I am defining all of my bindings within Global.asax.cs (a NinjectHttpApplication), in the CreateKernel method.
I also have an HTTP module that runs for all page requests. The module runs its logic on the PreRequestHandlerExecute after the CreateKernel method is already executed.
I would like to have the HTTP Module define a new binding by linking a class type to a specific instance variable that the module is responsible for constructing. Is this possible?
Basically, in the HttpModule, I am trying to run this:
IUserContext userContext = userContextManager.GetUserContext();
Kernel.Bind<IUserContext>().ToConstant(userContext).InRequestScope();
You should not be rebinding per-request – if you have 1000 requests in progress at a time, while it’s possible to have Ninject manage those registrations (e.g. via
.NamedBindings using the Binding Metadata facilities), you’re abusing the container for something it’s not supposed to do (for a start, are you going to do lots of busywork making theHttpModuleremove the registration after each request? All this is going to do is cause contention as the threads compete for access to the Kernel.Your
HttpModuleinstead should stash the relevant info somewhere suitable (HttpContext.Itemsis generally appropriate, but you might have a better idea?) and then useToMethod()instead to define a single callback that can retrieve the relevant data that has been stashed when a given request needs to use the info yourHttpModulehas stashed.Something like: