Why are my connections not closed even if I explicitly dispose of the DataContext?

Posted by Chris Simpson on Stack Overflow See other posts from Stack Overflow or by Chris Simpson
Published on 2010-04-21T19:55:07Z Indexed on 2010/04/21 20:03 UTC
Read the original article Hit count: 247

Filed under:
|
|

I encapsulate my linq to sql calls in a repository class which is instantiated in the constructor of my overloaded controller. The constructor of my repository class creates the data context so that for the life of the page load, only one data context is used.

In my destructor of the repository class I explicitly call the dispose of the DataContext though I do not believe this is necessary.

Using performance monitor, if I watch my User Connections count and repeatedly load a page, the number increases once per page load. Connections do not get closed or reused (for about 20 minutes).

I tried putting Pooling=false in my config to see if this had any effect but it did not. In any case with pooling I wouldn't expect a new connection for every load, I would expect it to reuse connections.

I've tried putting a break point in the destructor to make sure the dispose is being hit and sure enough it is. So what's happening?

Some code to illustrate what I said above:

The controller:

public class MyController : Controller
{
    protected MyRepository rep;

    public MyController ()
    {
        rep = new MyRepository();
    }
}

The repository:

public class MyRepository
{
    protected MyDataContext dc;

    public MyRepository()
    {
        dc = getDC();
    }

    ~MyRepository()
    {
        if (dc != null)
        {
            //if (dc.Connection.State != System.Data.ConnectionState.Closed)
            //{
            //    dc.Connection.Close();
            //}
            dc.Dispose();
        }
    }

    // etc
}

Note: I add a number of hints and context information to the DC for auditing purposes. This is essentially why I want one connection per page load

© Stack Overflow or respective owner

Related posts about linq-to-sql

Related posts about c#