Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Ninject call dispose and close the NHibernate Isession?

I'm using ASP.NET MVC 3 with Ninject and NHibernate.

When thinking of DI, i think the one who get the resource also makes sure to close it(In this case Ninject should be responsible)

But I'm not sure how Ninject works when using InRequestScope.

My code is:

Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();

I open a session and put it in I InRequestScope, but will Ninject take of closing my ISession when it is out of request scope?

like image 477
Luticka Avatar asked Mar 09 '11 08:03

Luticka


1 Answers

If I understand the code correctly the answer is yes. One of the ActivationStrategies used by Ninject is the DisposableStrategy, whose Deactivate method, calls Dispose on anything that implements IDisposable. If you're using the Ninject.Web.MVC extensions, the OnePerRequestModule will automatically clear the binding cache. This will call the Deactivate method on all the ActivationStrategies including the DisposableStrategy.

Since ISession implements IDisposable, it will be disposed. The default implementation of ISession, SessionImpl, closes the Session on Dispose.

If you're not using the Ninject.Web.MVC extensions the Cache will eventually be cleared, but may not happen right at EndRequest.

like image 86
Vadim Avatar answered Nov 02 '22 11:11

Vadim