2

I need to save some session/user related information in my MVC project. Since it should be unique and available throughout the lifetime of the session, I thought about "session-wide" singleton. I found several posts on this subject (for example here, here or here) but then I remembered reading this post about not using the Session object in a MVC application. Since this sounds like a generally bad idea, I thought about using the 4th version of Jon Skeet's singleton. In a couple of quick tests I wasn't able to see any violation of the singleton pattern per user session (i.e. only one object for every session was created). I might have missed something or might not have tested it correctly.

Is it safe to use this pattern for a session singleton in a MVC project (without saving the object in HttpContext.Current.Session or HttpContext.Current.Items)?

Community
  • 1
  • 1
Andrei V
  • 7,306
  • 6
  • 44
  • 64
  • 1
    A singleton is not your solution, since a single object will be created, and that object will be used for all requests. – Maarten Feb 06 '14 at 13:38
  • 1
    I would use either a database, or session. I don't see how the singleton can help in this case, unless the data you want to preserve is shared among users. – A Khudairy Feb 06 '14 at 13:58
  • @Maarten, that's what I'm going for: a single (state) object that can be accessed from any request during the current session. – Andrei V Feb 06 '14 at 14:11
  • @AKhudairy, a singleton object could be used from any action that needs to "store" some data about the current execution. It would be used pretty much as a static object, but would not be available to the entire application, but to the current session. – Andrei V Feb 06 '14 at 14:14
  • @AndreiV am just not getting it. if you come up with a good implementation please share it :) – A Khudairy Feb 07 '14 at 19:04

0 Answers0