Para
Para

Reputation: 2082

asp.net custom role provider nhibernate error

HI,

I am implementing a custom role provider in my nhibernate application I have a repository that I call whenever I want to access the nhibernate session.

So when my role provider initializes itself

public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) {

            base.Initialize(name, config);
            Repository = new Repository();
        }

Then I override

public override string[] GetRolesForUser(string username) {
        var users = Repository.QueryAll<Users>();

//I then filter and so on

    }

But when this function is called I always get an error that the NHibernate session is closed. I debugged the nhibernate source code and it turns out that the session here has a different guid that the session in my controllers(I am using ASP.NET MVC also). And this particular session is closed by the time I get here. I don't know who closes it. I know it is started when the application starts and only then.

Does anyone have any idea what I am doing wrong? I want to still use Nhibernate in this provider but not get the error any more. Thank you

Upvotes: 3

Views: 569

Answers (2)

Para
Para

Reputation: 2082

This is how I evetually fixed it.

in my repository class I had this:

public Repository()
{
    this.Session = SessionManager.GetCurrentSession();
}

I deleted the constructor entirely I put in this instead:

private ISession _session;
        protected ISession Session
        {
            get
            {
                if (_session == null)
                {
                    _session = SessionManager.GetCurrentSession();
                }
                return _session;
            }
        }

Upvotes: 1

Matt B
Matt B

Reputation: 8643

I had what appears to be the exact same problem. Don't forget that Role and Membership providers are only instantiated once and exist for the lifetime of the application. If you're using a Session per Web request pattern, the ISession will be closed after the first request and then any reference to an ISession internal to the provider will likely be null for subsequent requests.

You can get around this by injecting a reference to the ISessionFactory and calling GetCurrentSession, instead of directly holding a reference to an ISession.

Upvotes: 2

Related Questions