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();
}
}
}
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.