views:

2118

answers:

2

Hi,

Why is Session null in the constructors of Controllers? It can be accessed from Action methods. Presumably, because the MVC Routing framework is responsible for newing-up a Controller, it just hasn't (re-)instantiated the Session at that point.

Does anyone know if this is by design and, if so, why?

[I have managed to circumvent the problem by using a Lazy Loading Pattern.]

+4  A: 

The Session is injected later in the life-cycle. Why do you need the session in the constructor anyway? If you need it for TDD you should wrap the session into a mockable object.

Andrei Rinea
To add to Andrei Rinea, this is a specific example of the technique mentioned by him: http://iridescence.no/post/Using-Unit-Tests-to-Uncover-Design-Flaws.aspx
murki
I want to access the Session during my constructors so that I can have access to previously stored session information. Yes, I could override the OnActionExecuting method, but this certainly isn't an elegant solution.
Chris Arnold
+7  A: 

Andrei is right - it is null because when running under the ASP.NET MVC framework, the HttpContext (and therefore HttpContext.Session) is not set when the controller class is contructed as you might expect, but it set ("injected") later by the ControllerBuilder class. If you want a better understanding of the lifecycle you can either pull down the ASP.NET MVC framework (the source is available), or refer to: this page

If you need to access the Session then one way would be to override the "OnActionExecuting" method and access it there, as it will be available by that time.

However, as Andrei is suggesting, if your code is reliant on the Session then it could potentially be difficult to write unit tests, so perhaps you could consider wrapping the Session in a helper class which can then be swapped out for a different, non-web version when running under unit tests, therefore de-coupling your controller from the web.

Andrew W