2

Recently I've been integrating NHibernate into our server application that exposes multiple services. The core service manages multiple instances of a class, and I understood that it is recommended to use the session-per-request pattern. So far so good.

One of the other services is a Site Settings service, which effectively manages a singleton: there is only a single instance of SiteSettings. I can follow the session-per-request pattern with this service as well, but it seems odd. Do I really need to create a new session for each request here? Why not create a single session for the service and keep using it? One of the advantages of the session-per-request pattern is that the session does not eventually cache all objects in the model. However, since I will only ever load a single instance in the session, I think this should not be a concern. Would I be better off using IStatelessSession rather than ISession?

Are there other reasons to use session-per-request here? One concern that comes to mind is what happens in case of a disconnection to the DB. Can I keep using the same session even after a DB error?

As an aside, I was thinking of storing each setting in its own column, which means I have to update the schema as settings are changed. I found this post: NHibernate Web Application - Managing User Preferences, where one of the comments is against using a table to store such configuration settings. I'm having a hard time coming up with alternatives (short of serializing the whole class and storing it as a blob). Are there different approaches?

Community
  • 1
  • 1
hibernator
  • 145
  • 1
  • 6

1 Answers1

0

Sessions aren't thread safe so I think you'd want more than one for your singleton

Can I keep using the same session even after a DB error?

No, presumably that would throw an exception and you're not supposed to reuse sessions after an exception. IMHO you should stick with the session per request pattern.

Are there different approaches?

Can you use a different row per config setting? So your User object would have a child collection of UserSetting objects. Each UserSetting would just be a key value pair.

Jason Freitas
  • 1,587
  • 10
  • 18
  • Thanks for the reply. My Site Settings class uses locks so that only one request is proceesed concurrently, but the DB error argument settles the doubt. – hibernator Mar 15 '11 at 12:43
  • Using a row-per-config is interesting. It seems less type-safe, though (i.e. all values will be strings, unless I create a different column for each possible type). – hibernator Mar 15 '11 at 12:45