9

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?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Luticka
  • 639
  • 2
  • 6
  • 17
  • Can you explain how this differs from http://stackoverflow.com/questions/5221620/nhibernate-dependency-injection-close-isession-properly please and/or consider closing this - there are lots of dups of this quesxztion which is why none of them has a proper answer IMO? – Ruben Bartelink Mar 09 '11 at 09:42
  • The question you refer to has two answers which is contradictory and I actually got a good answers here, but now it is deleted? Maybe by you? – Luticka Mar 09 '11 at 12:06
  • @Lutica: Problem is that there are prob at least 2 more half-question+answers. @Darin deleted his as one of the maintainers (@Remo Gloor) pointed out a defficiency in his answer. @Darin should probably have left it and edited in a retraction as the fact that he misunderstood something is a learning experience for any of you. If I was able to delete posts, I certainly wouldnt - I'd comment at the answer to get it fixed or post an improved version if that didnt get me any results – Ruben Bartelink Mar 09 '11 at 17:29
  • @Lutica: The reason I stick my oar in here is that there's no decent answer, question or blog post on using Ninject with NHibernate in MVC3 properly that people can just be referred to, and each new question with half baked answers just makes the problem worse, not better. If someone could identify the best question I'd stick a bounty on it... – Ruben Bartelink Mar 09 '11 at 17:30
  • BTW S#arpArchitecture is often suggested as a place to look for best practice in this area, but you knew that from looking at the other answers! – Ruben Bartelink Mar 09 '11 at 17:31

1 Answers1

7

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.

Vadim
  • 17,897
  • 4
  • 38
  • 62