I am looking for some advice on the correct mechanism to use for getting a RavenDB IDocumentSession into my repositories in a true session-pr-request behaviour.
This is a greenfield MVC3 application, and I've gotten Ninject / Ninject.MVC3 using NuGet. RavenDB is running on an external server (i.e. non-embedded).
I've set up the Ninject module to return the right repositories, and also a session per request for them.
However - is it true that MVC3 will instantiate the controller for each action method? In that case, I can just allow MVC3/Ninject to inject my repositories and the sessions they need, no problem.
However, if a controller is reused across several requests, this might not work, as the repository hanging around from a previous request might now employ a session that is old and discarded.
I have looked at a few ways to do this - the above is the basic one. I have also tried to do something like an ActionFilterAttribute that gets a new session from the IoC container at the start of each request - but in that case, where should I put it?
Should my repository have a Session property it uses that actually gets the current session from the container each time? This would add coupling between the repository implementation and the IoC container, but otherwise should work I guess.
What is the proper way to do this? How are the cool kids doing it? Any help would be highly appreciated!
Unless you are doing something really funny with your controller factory, each controller instance will be used for a single requests. Controllers are not thread safe and will not usually survive beyond a single request.
I've written a comprehensive blog post about using Ninject's InRequestScope
so that IDocumentSession
is injected once per request. Ninject is great at managing scope for you.
http://www.dalsoft.co.uk/blog/index.php/2012/04/12/mvc-get-ravendb-up-and-running-in-5-minutes-using-ninject/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With