I’m building an ASP.NET MVC website with a WCF webservice backend that talks to the database via NHibernate. At the moment as POC I have one webservice called UserService which contains all the methods I need. The problem I have is that I have a DataRepository object which wraps the NHibernate configuration. When I create a new data repository object it loads the NHibernate configuration and mappings and cache etc. For my website in the users session, I want to keep this DataRepository object open for the life of their session as it doesn’t make sense to keep re-configuring NHibernate on a per-call basis and I want the same data repository to be available for all the webservice methods to benefit from NHibernate caching.
Is the answer here to make a static DataRepository object at the UserService.cs class level and configure the website to instantiate on a per-session basis, and would that mean each users session contains it’s own static datarepository object for the life of their session? Or is there a better way? Is there anything I haven’t thought of with the above approach?
I would suggest a better approach. Do not share the repository, share the hibernate’s session and make it injectable into the repository.
This way you can precisely control the lifetime of both, the repository and the session. In particular, you could have a shared session (in a request scope) but always create a new (transient) repository.