Ninject and OnePerRequestModule
Asked Answered
U

1

12

I have recently tried out Ninject with the Ninject.Web.Mvc extension, and I've noticed something peculiar and, while not breaking, confusing.

In the NinjectHttpApplication abstract class, there is a constructor defined as follows..

    /// <summary>
    /// Initializes a new instance of the <see cref="NinjectHttpApplication"/> class.
    /// </summary>
    protected NinjectHttpApplication()
    {
        this.onePerRequestModule = new OnePerRequestModule();
        this.onePerRequestModule.Init(this);
    }

I have placed a debugger breakpoint here, and this gets called a few times. I cannot find any real documentation on it. In the implementation code, there is this line that catches my eye.

            if (kernel.Settings.Get("ReleaseScopeAtRequestEnd", true))
            {
                OnePerRequestModule.StartManaging(kernel);
            }

My questions are as follows...

  • What is OnePerRequestModule
  • Why is this constructor being called multiple times?
  • What is the purpose of this StartManaging method, if the constructor is called multiple times?
Uhl answered 16/2, 2011 at 15:27 Comment(1)
related: #15778824Ironware
H
13

The OnePerRequestModule removes InRequestScope()d objects from the Kernel's Cache upon completion of each HTTP Request.

The NinjectHttpApplication ctor is called multiple time because IIS creates several of them. One NinjectHttpApplication can only handle one request at a time. So IIS generates (at least) one instance per thread.

StartManaging tells all OnePerRequestModules that they shall release the InRequestScoped objects from the specified Kernel after the Request has Ended.

Hawkes answered 17/2, 2011 at 9:27 Comment(2)
So this is something I am okay to leave intact? It isn't something I need to worry about?Uhl
@Uhl Doc should be much clear now, see https://mcmap.net/q/412078/-do-i-need-to-register-ninject-oneperrequestmodule-with-ninject-web-mvc-3-0 and github.com/ninject/Ninject.Web.Common/wiki/InRequestScopeIronware

© 2022 - 2024 — McMap. All rights reserved.