Don Fitz
Don Fitz

Reputation: 1174

ServiceStack With Funq and FuentNHibernate Sesssion per Request

I'm trying to use FluentNHibernate in ServiceStack with the Funq IoC container on a session-per-request basis and I'm running into a problem where upon the second request to my service, I get an ObjectDisposedException. Shouldn't Funq create a new Session for each request?

My understanding is that by using ReusedWithin(ReuseScope.Request) in Funq, each request would get a new ISession, but that's only happening for the first request. In my AppHost I have the following:

public static NH.ISession CurrentSession
    {
        get
        {
            SessionFactory = GetFactory();
            NH.ISession session = SessionFactory.OpenSession();
            return session;
        }
    }

    private static NH.ISessionFactory GetFactory()
    {
        return Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
            .ConnectionString(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)).Mappings(m =>
            { m.FluentMappings.AddFromAssemblyOf<Case>(); })
            .BuildSessionFactory(); 
    }

And the registration with the container:

            container.Register<NH.ISession>(c => CurrentSession).ReusedWithin(Funq.ReuseScope.Request);
            container.Register<ILog>(c => LogManager.GetLogger(GetType()));  

Upvotes: 2

Views: 392

Answers (1)

Don Fitz
Don Fitz

Reputation: 1174

So I figured out what my problem was. When using a request scope of per-request in Funq for a NHibernate ISession, make sure the other services that depend on it are also scoped per-request or their backing dependency (ISesssion in this case) will be disposed of on the next request. I changed my container registration to the below:

container.Register<NH.ISession>(c => CurrentSession).ReusedWithin(Funq.ReuseScope.Request);
            container.Register<ILog>(c => LogManager.GetLogger(GetType()));
            container.Register<IRequestService>(c => new Services.RequestService(c.Resolve<NH.ISession>(), c.Resolve<ILog>())).ReusedWithin(Funq.ReuseScope.Request);

The key is that the Request service must also be scoped per-request.

Upvotes: 6

Related Questions