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

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: Ensuring Deterministic Dispose calls in a Request Processing cycle

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.

While it's trivially true that generating and Disposing a fresh Kernel per Request will work, it's definitely not recommended. Either of following mechanisms can be used to ensure deterministic Dispose calls:

Use the Ninject.Web.Common package

The Ninject.Web.Common package generates code to register the OnePerRequestModule for you in NinjectWebCommon.cs:-

DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)))

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 ASP.NET's 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>