-
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).
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:
- Use the
Ninject.Web.Common
extensions that register theOnePerRequestModule
for you. - Register the
OnePerRequestModule
with IIS/ASP.NET (see below for more detail) - Create your Kernel and Dispose it for each request (this is not recommended)
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>