Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've recently been learning (and struggling with) integrating AutoFac, NHibernate & ASP.NET Web API. I have found several tutorials with code that did not work as anticipated but managed to finally find a working solution.

Essentially what I'm doing is registering a singleton of my SessionFactory to the WebApiApplication.SessionFactory object, registering a per-API-request ISession & IClientRepository. After these are registered, I'm creating a controller with a DI'ed IClientRepository (which in turn has an ISession injected which creates a new session as seen in the code below).

My controllers are marked with a custom TranscationActionFilterAttribute to bind (or create) a session. The issue I was initially encountering while implementing this pattern is that considering a new session is created every time IClientRepository was injected with an ISession, the session was never automatically bound and the code in my Transcation action filter would always create an extraneous session, thereby making updates and deletes not function properly. I got around this by binding the ISession in the constructor of my ClientRepository.

Is this safe?


public class WebApiApplication : System.Web.HttpApplication
    public static ISessionFactory SessionFactory { get; set; }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)

    protected void Application_Start()


        var configuration = GlobalConfiguration.Configuration;
        var builder = new ContainerBuilder();
        // Register ISessionFactory as Singleton
        builder.Register(x => NHibernateConfigurator.BuildSessionFactory()).SingleInstance();

        // Register API controller types using assembly scanning.
                        .Where(t =>
                        !t.IsAbstract && typeof(ApiController).IsAssignableFrom(t));

        // Register ISession as instance per web request
        builder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).InstancePerApiRequest();

        // Register clients controller as instance per web request

        // Register all controllers

        // Override default dependency resolver to use Autofac
        var container = builder.Build();

        // Set the dependency resolver implementation.
        var resolver = new AutofacWebApiDependencyResolver(container);
        configuration.DependencyResolver = resolver;


public class TransactionAttribute : System.Web.Http.Filters.ActionFilterAttribute
    private ISessionFactory SessionFactory { get; set; }

    public TransactionAttribute()
        SessionFactory = WebApiApplication.SessionFactory;

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        if (!CurrentSessionContext.HasBind(SessionFactory))

        var session = SessionFactory.GetCurrentSession();

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        var session = SessionFactory.GetCurrentSession();
        var transcation = session.Transaction;
        if (transcation != null && transcation.IsActive)
        session = CurrentSessionContext.Unbind(SessionFactory);

And the constructor for my repository:

    public ClientRepository(ISession session) 
        if (session == null) throw new ArgumentNullException("nhSession");
        this._session = session;
share|improve this question

This is not going to answer your question directly but..

By definition I suppose that Code Review allows me to suggest and share subjective ideas (to be determined)...

By convention, stuff that needs to be done on the application start can be located in a App_Start folder.

Here's a template for AutoFac, ~/App_Start/AutofacMvcConfig.cs:

using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Models;
using MvcApplication.App_Start;

[assembly: WebActivator.PreApplicationStartMethod(typeof(AutofacMvcConfig), "Start")]

namespace MvcApplication.App_Start
    public class AutofacMvcConfig
        public static void Start()
            var builder = new ContainerBuilder();


            var container = builder.Build();

            // Install-Package Autofac.Mvc3
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));


Keywords: mvc, unit of work, autofac, actionfilterattribute

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.