Don't flush the session after an exception occurs - NHibernate

后端 未结 3 1532
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 01:02

I am developing a ASP.NET MVC web app under .NET 3.5, NHibernate and hosted on Windows Azure. When, the webapp is run from the local development fabric it works fine. Yet, w

3条回答
  •  爱一瞬间的悲伤
    2021-01-05 02:00

    I have finally found a solution to my own problem. In case people would be interested, I am posting the solution here.

    public class SimpleRoleProvider : RoleProvider 
    {
        // isolated session management for the RoleProvider to avoid
        // issues with automated management of session lifecycle.
    
        public override string[] GetRolesForUser(string username)
        {
            using (var session = GlobalSetup.SessionFactory.OpenSession())
            {
                var users = new UserRepository(session);
                var user = users.Get(username);
    
                // no role if user is not registered
                if (null == user) return new string[0];
    
                // default role for registered user
                return user.IsManager ? new[] {"Manager", "User"} : new[] {"User"};
            }
        }
    }
    

    Basically what was happening is that the RoleProvider repository does not seem to have the same lifecycle than regular in-view / in-controller repositories. As a result, at the time the RoleProvider is called, the NHibernate session has already been disposed causing the exception observed here above.

    I have replaced the code by the following one here above. This one has its own NHibernate session management, and ends up working fine.

提交回复
热议问题