Pregunta

I'm using Ninject 2.0 with an MVC 2/EF 4 project in order to inject my repositories into my controllers. I've read that when doing something like that, one should bind using InRequestScope(). When I do that, I get a new repository per request, but the old repositories aren't being disposed. Since the old repositories are remaining in memory, I get conflicts with multiple ObjectContexts existing at the same time.

My concrete repositories implement IDisposable:

public class HGGameRepository : IGameRepository, IDisposable
{
    // ...

    public void Dispose()
    {
        if (this._siteDB != null)
        {
            this._siteDB.Dispose();
        }
    }
}

And my Ninject code:

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel kernel = new StandardKernel(new HandiGamerServices());

    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        try
        {
            if (controllerType == null)
            {
                return base.GetControllerInstance(requestContext, controllerType);
                // return null;
            }
        }
        catch (HttpException ex)
        {
            if (ex.GetHttpCode() == 404)
            {
                IController errorController = kernel.Get<ErrorController>();
                ((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);

                return errorController;
            }
            else
            {
                throw ex;
            }
        }

        return (IController)kernel.Get(controllerType);
    }

    private class HandiGamerServices : NinjectModule
    {
        public override void Load()
        {
            Bind<HGEntities>().ToSelf().InRequestScope();
            Bind<IArticleRepository>().To<HGArticleRepository>().InRequestScope();
            Bind<IGameRepository>().To<HGGameRepository>().InRequestScope();
            Bind<INewsRepository>().To<HGNewsRepository>().InRequestScope();
            Bind<ErrorController>().ToSelf().InRequestScope();
        }
    }
}

What am I doing wrong?

¿Fue útil?

Solución

I'm quite sure that you are wrong about the guess that your objects are not disposed. This just does not happen when you think it will happen. But the fact that this does happen later should not give you any problems with ObjectContexts unless you are doing something wrong. With a high load you will have a lot of ObjectContexts at the same time anyway.

What can become a problem though is that the memory usage increases. That's why the request scope needs to be released actively. The Ninject MVC extensions will take care of that. Otherwise have a look at the OnePerRequestModule to see how it is done:

https://github.com/ninject/Ninject.Web.Common/blob/master/src/Ninject.Web.Common/OnePerRequestHttpModule.cs
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top