NHibernate ISession in ASP.NET Core: DI scope vs CurrentSessionContext — which should own the session?
0 reputation · 29 Oct 2023, 20:01 UTC
I'm integrating NHibernate 5.4 with ASP.NET Core 8 and need to decide how the ISession lifecycle should be managed. NHibernate's built-in CurrentSessionContext implementations (web, call) predate ASP.NET Core's middleware pipeline and IServiceScope model, so the two boundaries don't line up cleanly.
The community NHibernate.AspNetCore package registers ISessionFactory as a singleton and ISession as scoped, but it also binds sessions to CurrentSessionContext via middleware. That means a constructor-injected ISession and sessionFactory.GetCurrentSession() could resolve to different instances if middleware ordering or scope handling is off — which would break lazy-loading proxies and change tracking in subtle ways.
I want one authoritative session per HTTP request, shared by repositories that inject ISession and legacy code that calls GetCurrentSession(). I'm unsure whether to abandon CurrentSessionContext entirely or write a custom ICurrentSessionContext that delegates to IHttpContextAccessor.HttpContext.RequestServices.
- Are injected
ISessionandGetCurrentSession()guaranteed to be the same instance underAddNHibernate(), or only under specific middleware ordering? - Is a custom
ICurrentSessionContextdelegating to the DI scope a sound approach, and are there documented pitfalls? - Does either choice behave differently for background work outside a request scope?