25

I was surprised to find that at least one of my objects created by Ninject is not disposed of at the end of the request, when it has been defined to be InRequestScope

Here's the object I'm trying to dispose:

Interface:

public interface IDataContext : IDisposable
{
    MessengerEntities context { get; set; }
}

MessengerEntities is Entity Framework's implementation of ObjectContext -- my context object.

Then I create a concrete class like so:

public class DataContext : IDataContext
{
    private MessengerEntities _context = new MessengerEntities();
    public MessengerEntities context
    {
        get
        {
            return _context;
        }
        set
        {
            _context = value;
        }
    }
    #region IDisposable Members

    public void Dispose()
    {
        context.Dispose();
    }

    #endregion
}

And then I have a Ninject controller factory like so (this is modeled on the Steve Sanderson MVC 2 book):

public class NinjectControllerFactory : DefaultControllerFactory
{
    // a Ninject "kernel" is the thing that can supply object instances
    private IKernel kernel = new StandardKernel(new MessengerServices());

    // ASP.NET MVC calls this to get the controller for each request
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
            return null;
        return (IController)kernel.Get(controllerType);
    }

    private class MessengerServices : NinjectModule
    {
        public override void Load()
        {
            Bind<IDataContext>().To<DataContext>().InRequestScope();
            Bind<IArchivesRepository>().To<ArchivesRepository>().InRequestScope();
            Bind<IMessagesRepository>().To<MessagesRepository>().InRequestScope();
        }
    }
}

Now, when I put a breakpoint at the call to context.Dispose() in the DataContext object and run the debugger, that code never gets executed.

So, the evidence suggests that Ninject does not dispose of objects when they go out of scope, but simply creates new objects and relies on the garbage collector to get rid of them at a time of its choosing.

My question is: should I be concerned about this? Because I am -- I would think Ninject would dispose of any object that implements IDisposable.

UPDATE: I downloaded the Ninject Mvc extensions (for MVC 3) and this is now how I'm doing the MvcApplication and the binding, and it does seem to be disposing of my context object.

In global.asax:

public class MvcApplication : NinjectHttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected override Ninject.IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }

    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
}

and

public class EFBindingModule : NinjectModule
{
    public override void Load()
    {
        Bind<IDataContext>().To<DataContext>().InRequestScope();
        Bind<IArchivesRepository>().To<ArchivesRepository>().InRequestScope();
        Bind<IMessagesRepository>().To<MessagesRepository>().InRequestScope();
    }
}

Everything else remains the same.

Cynthia
  • 2,100
  • 5
  • 34
  • 48

1 Answers1

15

Ninject will dispose your objects as soon as the request object is collected by the GC. But normally this takes some time. But there is a way to force early disposal after the request ended. The best way is to use Ninject.Web.MVC http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/ instead of implementing your own ControllerFactory. The other way is to configure your application to use the OnePerRequestModule.

Remo Gloor
  • 32,665
  • 4
  • 68
  • 98
  • 4
    Awesome, I think it's working! I'm not quite sure how -- but I downloaded the Ninject MVC3 extensions, extended NinjectHttpApplication in the Global.asax, and created a class derived from NinjectModule to define my bindings, and voila, it is now calling Dispose on my DataContext class. (I will add the code I'm using to my question and you can let me know if I'm still not doing it right.) Thank you! – Cynthia Mar 01 '11 at 00:40
  • 2
    I'm using `Ninject.Web.MVC4` and my `IDataContext` which is `InRequestScope()` is not being disposed. I manually added `` to `system.web/httpModules` and that isn't working either. Any suggestions? – epalm Sep 18 '14 at 21:57
  • 3
    Strange. Disposing on GC seems like a defeat of purpose to me. Why would Ninject documentation ( https://github.com/ninject/ninject/wiki/Object-Scopes ) advertise Dispose on end of request if it doesn't do so? – Stilgar Dec 04 '14 at 13:08
  • I have the same issue, except it sometimes disposes, and sometimes not. I am using a Web API 2 and not MVC. will this MVC extension work with WebApi ? – Gerrie Pretorius May 07 '19 at 16:22