In our MVC application we predominantly use Ninject to inject dependencies into controllers. As such, our default lifetime scope is InRequestScope(). We have now added an IHttpModule that uses common dependencies as the controllers (i.e., UserService). The problem is that HttpModules can be pooled by ASP.NET and IIS and reused over multiple requests. Because the injected dependencies are set to InRequestScope, subsequent requests will often get an ObjectDisposedException when referencing the injected dependencies inside the HttpModule. How can I specify InRequestScope() for the UserService when injecting into a controller and InScope() when injecting into an HttpModule.
Here is a simplified version of our registration:
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start(){
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop(){
bootstrapper.ShutDown();
}
private static IKernel CreateKernel(){
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Bind<IHttpModule>().To<CustomModule>(); // needs a UserService
kernel.Bind<IUserService>().To<UserService>().InRequestScope(); // injected into controllers and the CustomModule
DependencyResolver.SetResolver(new Services.NinjectDependencyResolver(kernel));
return kernel;
}
}