NHibernate session per request

Topics: Core, General
Dec 22, 2011 at 9:29 AM

I'm currently trying to figure out if i can split the behaviour of NHibernate. I've orchard running with default settings and a custom servicehost. I think that both are running the same NHibernate configuration. Is there a way to configure the session behaviour for both independent of eachother?

Looking at the ISessionFactoryHolder it's a SingletonDependency, this could be a problem, but i'm not sure.

Can someone put me into the right direction, since i want to make sure that each Wcf request creates a new NHibernate session

Just like here
http://www.nikosbaxevanis.com/bonus-bits/2011/03/nhibernate-session-per-request-with-wcfoperationsessioncontext.html

Dec 22, 2011 at 10:19 AM

Nevermind, again it was related to LifetimeScope.Resolve which returns a existing instance including an existing instance of the SessionLocator.

    public static class LifetimeScopeExtensions
    {
        public static T ResolveNew<T>(this ILifetimeScope scope)
        {
            IWorkContextAccessor workContextAccessor = scope.Resolve<IWorkContextAccessor>();
            WorkContext workContext = workContextAccessor.GetContext();
            if (workContext == null)
            {
                using (IWorkContextScope workContextScope = workContextAccessor.CreateWorkContextScope())
                {
                    ILifetimeScope lifetimeScope = workContextScope.Resolve<ILifetimeScope>();
                    return lifetimeScope.Resolve<T>();
                }
            }
            else
            {
                ILifetimeScope lifetimeScope = workContext.Resolve<ILifetimeScope>();
                return lifetimeScope.Resolve<T>();
            }        
        }
 
        public static object ResolveNew(this ILifetimeScope scope, Type type)
        {
            IWorkContextAccessor workContextAccessor = scope.Resolve<IWorkContextAccessor>();
            WorkContext workContext = workContextAccessor.GetContext();
            if (workContext == null)
            {
                using (IWorkContextScope workContextScope = workContextAccessor.CreateWorkContextScope())
                {
                    ILifetimeScope lifetimeScope = workContextScope.Resolve<ILifetimeScope>();
                    return lifetimeScope.Resolve(type);
                }
            }
            else
            {
                ILifetimeScope lifetimeScope = workContext.Resolve<ILifetimeScope>();
                return lifetimeScope.Resolve(type);
            }        
        }
    }