Database permissions in MVC with NHibernate

2019-08-19 04:19发布

问题:

I'm working on an intranet MVC web application, using Fluent NHibernate.

As everyone knows, creating the necessary ISessionFactory is heavy, and therefore should be done only once. Hence, I create it in the Global.asax file during Application_Start, then cache it in the application for future use.

The problem is that I only want to give access to users who already have permissions over the database.

This could theoretically be solved by defining Integrated Security=SSPI in the connection string (rather than by providing an SQL username and password).

However, this raises an error during Fluently.Configure, because the configuration occurs during Application_Start, which is being run by the process hosting the application, which does not have permissions to connect to the DB.

How do I solve this issue?

回答1:

You could initialize it in BeginRequest instead of Application_Start:

private static bool _initialized = false;
private static object _syncRoot = new object();

protected void Application_BeginRequest(object source, EventArgs e)
{
    if (_initialized)
    {
        return;
    }

    lock (_initialized)
    {
        if (_initialized)
        {
            return;
        }

        // Initialize the session factory here and cache it

        _initialized = true;
    }
}