Question

I'm developing an ASP.NET (Razor v2) Web Site, and using the WebMatrix.Data library to connect to a remote DB. I have the Database wrapped in a singleton, because it seemed like a better idea than constantly opening and closing DB connections, implemented like so:

public class DB
{
    private static DB sInstance = null;
    private Database mDatabase = null;

    public static DB Instance
    { 
        get
        {
            if (sInstance == null)
            {
                sInstance = new DB();
            }
            return sInstance;
        }
    }

    private DB()
    {
        mDatabase = Database.Open("<Connection String name from web.config>");

        return;
    }

    <Query Functions Go Here>
}

("Database" here refers to the WebMatrix.Data.Database class)

The first time I load my page with the form on it and submit, a watch of mDatabase's Database.Connection property shows the following: (Sorry, not enough rep to post images yet.)

http://i.stack.imgur.com/jJ1RK.png

The form submits, the page reloads, the submitted data shows up, everything is a-ok. Then I enter new data and submit the form again, and here's the watch:

http://i.stack.imgur.com/Zorv0.png

The Connection has been closed and its Connection String blanked, despite not calling Database.Close() anywhere in my code. I have absolutely no idea what is causing this, has anyone seen it before?

I'm currently working around the problem by calling Database.Open() before and Database.Close() immediately after every query, which seems inefficient.

Was it helpful?

Solution

The Web Pages framework will ensure that connections opened via the Database helper class are closed and disposed when the current page has finished executing. This is by design. It is also why you rarely see connections explicitly closed in any Web Pages tutorial where the Database helper is used.

It is very rarely a good idea to have permanently opened connections in ASP.NET applications. It can cause memory leaks. When Close is called, the connection is not actually terminated by default. It is returned to a pool of connections that are kept alive by ADO.NET connection pooling. That way, the effort required to instantiate new connections is minimised but managed properly. So all you need to do is call Database.Open in each page. It's the recommended approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top