Skip to content
bartelink edited this page Apr 3, 2013 · 9 revisions

#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).

For detailed information about scopes see read the Object Scopes article in the Ninject core documentation.

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.

IMPORTANT

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:

  1. Use the Ninject.Web.Common extensions that register the OnePerRequestModule for you.
  2. Register the OnePerRequestModule with IIS/ASP.NET (see below for more detail)
  3. Create your Kernel and Dispose it for each request (this is not recommended)

Manually registering OnePerRequestModule (e.g. if you're not using Ninject.Web.Common)

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 (though it is generally preferred to have the Ninject.MVC* NuGet packages generate code to register it instead):

<configuration>
  <system.web>
    <httpModules>
      <add name="OnePerRequestModule" type="Ninject.OnePerRequestModule"/>
    </httpModules>
  </system.web>
</configuration>