Does anyone have any tips or best practices regarding how Autofac can help manage the NHibernate ISession Instance (in the case of an ASP.NET MVC application)?
Does anyone have any tips or best practices regarding how Autofac can help manage
Share
I’m not overly familiar with how NHibernate sessions should be handled. That said, Autofac have excellent instance lifetime handling (scoping and deterministic disposal). Some related resources are this article and this question. Since you’re in ASP.Net MVC land make sure you also look into the MVC integration stuff.
To illustrate the point, here’s a quick sample on how you can use Autofac factory delegates and the
Ownedgeneric to get full control over instance lifetime:The container setup to get this to work is quite simple. Notice that we don’t have to do anything to get the
Func<>andOwned<>types, these are made available automatically by Autofac:Update: my reasoning here is that, according to this NHibernate tutorial, the lifetime of the session instance should be that of the “unit of work”. Thus we need some way of controlling both when the session instance is created and when the session is disposed.
With Autofac we get this control by requesting a
Func<>instead of the type directly. Not usingFunc<>would require that the session instance be created upfront before the controller instance is created.Next, the default in Autofac is that instances have the lifetime of their container. Since we know that we need the power to dispose this instance as soon as the unit of work is done, we request an
Ownedinstance. Disposing the owned instance will in this case immediately dispose the underlying session.