Reputation: 10081
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!
Upvotes: 6
Views: 1548
Reputation: 11107
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.
Upvotes: 3
Reputation: 33
I think that you should avoid going on with Controllers.
It may help sometime: If session state is disabled we should no longer try to use the Session Property on the Controller as it will be null. Turning off session state and using the Session Property will give you the dreaded “object reference not set to an instance of object” error.
Upvotes: -1
Reputation: 22956
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.
Upvotes: 12