0

I wonder what is the best way to manage NHibernate Session Context when using NH data layer from Xsockets controller. Particularly I refer to self hosted winservice/console application or Azure worker role, where HTTPContext is not available. Of course there is always an option to create and dispose session per call, but that means a performance hit, so better reuse sessions in some way. My controller provides API for CRUD operations in underlying NH repository and is pushing updates to relevant subscribers when certain records are updated in DB.

Your ideas appreciated :)

Alex Michel
  • 416
  • 3
  • 13

2 Answers2

0

Since XSockets has state is will be bad for your database if you open the connection in the OnOpen event since the connection will remain open as long as the socket is open. Best is to use the repository only in the methods calling the CRUD operations as briefly as possible.

To get the instance of your repository should not be a bottleneck in this case.

I will be happy to review any code you might have.

Regards Uffe

Uffe
  • 2,275
  • 1
  • 13
  • 9
  • Thanks Uffe. Luckily I am only about to write this implementation, but I want to reuse the data layer used in other service. So your suggestion is to create and dispose session on every call to controller methods? NHibernate session is more that just SQL connection that you most probably get from pool. It is caching entities, etc... From experience I know that it is quite expensive to create every time and when possible using ThreadStatic context gave significant performance boost. – Alex Michel Aug 30 '14 at 16:52
  • I have never had any issues getting the service instance inside the method encapsulated in a using scope. A sample on pastepin http://pastebin.com/trv9TRCP – Uffe Aug 31 '14 at 06:29
  • This sample is of NInject IOC container resolving service. I am talking about NHibernate session context policy:http://nhforge.org/wikis/reference2-0en/context-sessions.aspx – Alex Michel Aug 31 '14 at 12:59
  • 1
    XSockets has state built-in so we do not need sessions. If you want to use sessions anyway it is probably doable. You can also store data between connections in the XSockets storage. So there is no need for sessions there either. But I guess you do something with sessions in your service? Probably the wrong forum to have a long discussion... :) – Uffe Aug 31 '14 at 14:03
0

I'm using StructureMap to handle dependencies and create a NestedContainer to handle session per request. Don't have to mess with CurrentSessionContext or HttpContext anymore for storing session.

http://structuremap.github.io/the-container/nested-containers/

You could even just create a middleware UnitOfWork if you are using OWIN with WebAPI.

Joey V.
  • 1,866
  • 1
  • 22
  • 18