views:

34

answers:

1

The title is a bit complicated, but it fits my problem. I have a complex object that acts more like a service that I need to expose within the scope of a user's session. The majority of the application will exist within a page or two and numerous ajax calls for dynamic interaction with the service. I'm still getting used to MVC so excuse the ignorance if the solution is easy. How do I expose an instance of the service per session to my controllers?

Thanks in advance!

A: 

Also see this SO question: How does the session state work in MVC 2.0?

That answer contains a nice code sample such as the following about accesssing per-user session state from a controller class.

   // from example
   if (Session["QuestionAnswers"] != null)
   {
        return (List<QuestionAnswer>)Session["QuestionAnswers"];
   }

You can use regular ASP.NET Session state to store a complex object for a particular user.

You can store anything in session state, including your "complex object" value.

MSDN Session State quote:

ASP.NET session state enables you to store and retrieve values for a user as the user navigates the different ASP.NET pages that make up a Web application

The following quotes from Scott Guthrie (a Corporate Vice President in the Microsoft Developer Division) support it use of regular session state in MVC:

Scottgu Quotes about MVC & Session State support:

Non-UI features in ASP.NET today like Forms Authentication, Windows Authentication, Membership, Roles, Url Authorization, Caching, Session State, Profiles, Health Monitoring, Configuration, Compilation, Localization, and HttpModules/HttpHandlers all fully support the MVC model.

-- http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx

Although the way you structure application flow will be different, I think you'll be pleasantly surprised by the amount of knowledge overlap that exists. Authentication, Authorization, Caching, Configuration, Compilation, Session State, Profile Management, Health Monitoring, Administration, Deployment, and many, many other things are exactly the same. MVC views are also .aspx pages (that use .ascx user controls and .master files). So the concept re-use is quite heavy there as well.

-- http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

John K
Is this approach "heavy" though? In other words, is performance going to degrade seriously with a large object in session?
BennyT
Depends on your app. For example: how many users and how many objects, how much memory. At a "tipping point" of usage you'll likely want to reconstruct complex objects per user instead of keep them around memory. However only you know when your custom app reaches that point of needed such an optimization. Unless you know for sure, it's suggested to not pre-optimize.
John K