if i have a static class with a dbcontext field, does that mean the connection stays open for the life of the application?

StackOverflow https://stackoverflow.com/questions/18664782

Question

This is probably an obvious question... Below is a skeleton of a static class I am using for interactions with the database. My question is this: If a static class lives for the duration of the application, then does that mean the the field _context will have a connection that remains open for that long as well?, or if I wrap the calls I make with a using statement, can I be confident that the connection will only open and close as expected?

public static class MyStaticClass
{
    private static dbEntities _context;

    static MyStaticClass()
    {
        _context = new dbEntities();
    }

    private static void UpdateContext()
    {
        _context = new dbEntities();
    }

    public static bool DoSomething(int id)
    {
        using (var context = _context)
        {
            var result = (from x in context.table.where(p=>p.id == id) select x).FirstOrDefault();
        }
    }
}
Was it helpful?

Solution

If you have a static context then it means that all of the resources held by that object will be held for the duration of the application, yes.

If you wrap uses of it in a using then you'll simply be using a disposed object after the first call, and it won't work.

Instead you should simply create new data contexts at the smaller scope. There isn't a need for it to be a long lived object. Connection pooling helps to ensure that the cost of creating several short lived contexts isn't much more expensive than one long lived context.

Have each context represent one logical operation, and then make a new one for the next operation.

OTHER TIPS

You need to make sure that dbcontext class is thread safe or you going to have very serous issues if your application have more that one simultaneous user, one user can close the connection for the other or to receive data that he did not asked for.

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