-
Notifications
You must be signed in to change notification settings - Fork 40
InRequestScope
#InRequestScope
For web applications you can use InRequestScope() to have Ninject create a single instance for each request handled by your application. For InRequestScope() bound instances, Ninject will use HttpContext.Current in case of HTTP applications and OperationContext.Current in case of WCF requests as the scoping object. Note that you do not have to use InRequestScope() to use Ninject with your web application - you can use InTransientScope() and even InSingletonScope() if those behaviors are desired. The main reason for using InRequestScope() is to make sure that a single instance of an object is shared by all objects created via the Ninject kernel for that HTTP request (e.g. to share an object that is expensive to create).
NOTE: InRequestScope is provided by an extension method. In order to use it you need to add the namespace Ninject.Web.Common to your usings.
For detailed information about Scopes and Disposal, see read the Object Scopes article in the Ninject core documentation.
The Ninject kernel maintains a weak reference to scoping objects and will automatically Dispose of objects associated with a scoping object when the weak reference to it is no longer valid. Since InRequestScope() uses HttpContext.Current or OperationContext.Current as the scoping object, any associated objects created will not be destroyed until HttpContext.Current or OperationContext.Current is destroyed. Since IIS/ASP.NET manages the lifecycle of these objects, disposal of your objects is tied to whenever IIS/.NET decides to destroy them and that may not be predictable.
To get more deterministic behavior, you can do any of the following:
- Use the
Ninject.Web.MVC*packages to generate code to register theOnePerRequestModulefor you, i.e., the following code fragment inNinjectWebCommon.cs:DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule))) - Register the
OnePerRequestModulewith IIS/ASP.NET (see below for more detail) - Create your Kernel and Dispose it for each request (this is not recommended)
Manually registering OnePerRequestModule in web.config (e.g. if you're not using a Ninject.Web.MVC* NuGet Package)
OnePerRequestModule is an IHttpModule provided by Ninject that will hook the EndRequest callback and Dispose instances associated with HttpContext.Current as part of the Ninject Kernel's Deactivation of tracked instances for you. You can register it using the following XML in your Web.Config:
<configuration>
<system.web>
<httpModules>
<add name="OnePerRequestModule" type="Ninject.OnePerRequestModule"/>
</httpModules>
</system.web>
</configuration>