ObjectContext is not designed to be a long-lasting object. Consider it rather like an implementation of Unit of Work pattern. So the second option is probably better.
preferred pattern for disposing an object context
Question
In an Azure worker role is which of the following patterns is recommended for disposing an objectcontext. Also, would using either of these patterns affect the connection pooling in a different way?
public override void Run()
{
DatabaseObjectContext ctx = new DatabaseObjectContext()
while (condition)
{
ctx.Dosomething();
}
ctx.Dispose();
}
vs
public override void Run()
{
while (condition)
{
DatabaseObjectContext ctx = new DatabaseObjectContext()
ctx.Dosomething();
ctx.Dispose();
}
}
Solution
OTHER TIPS
If I had to choose between the two (i.e. I cannot or is too complicated to implement as Barlomieij said a UoW pattern), I'd choose the first, removing the ctx.Dispose() at the end and replacing it by wrapping everything in a using statement.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow