Question

This question has been asked many times before, but for the life of me I can not get Ninject to dispose services that are InRequestScope. I have looked at all the answers and most of them tell the user to use Ninject.MVC3 or OnePerRequestHttpModule. I am using Ninject.MVC5.

Here is how to get to where I am:

Using VS2013

  • Add new project (ASP.NET Web application)
  • Choose MVC and no authentication
  • Add NuGet reference to Ninject.MVC5
  • Add an interface to project:

    public interface IBlah : IDisposable
    {
        void DoSomething();
    }
    
  • Add an implementation for the interface:

    public class Blah : IBlah
    {
        private static int _count;
    
        public Blah()
        {
            _count++;
            Debug.WriteLine("Blah nr {0} created", _count);
        }
    
        public void DoSomething()
        {
            Debug.WriteLine("DoSomething called");
        }
    
        public void Dispose()
        {
            _count--;
            Debug.WriteLine("Blah disposed. Still left {0}", _count);
        }
    }
    
  • Open up home controller and add the following ivar and constructor:

    private readonly IBlah _blah;
    
    public HomeController(IBlah blah)
    {
        _blah = blah;
    }
    
  • Add the following to Index action:

    _blah.DoSomething();
    
  • Open NinjectWebCommon and add the following line to RegisterServices method

    kernel.Bind<IBlah>().To<Blah>().InRequestScope();
    
  • Debug the project and look at Debug output you will see (among system messages)

    "Blah nr 1 created"
    "DoSomething called"
    
  • Hit refresh in the browser and you will see

    "Blah nr 2 created"
    "DoSomething called"
    
  • Nothing gets output for disposing, also breakpoint inside Dispose is never hit.

My test solution can be downloaded here: http://www.upload.ee/files/4044477/NinjectTest.zip.html

What the hell am I doing wrong???


UPDATE 15 May 2014

There is now a new version (3.2.2) of Ninject.Web.Common package available for NuGet that has fixed the bug.

Was it helpful?

Solution

I suggest that is related to this ninject issue: https://github.com/ninject/ninject/issues/132#issuecomment-42459686

OTHER TIPS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top