The rule of the thumb is: do not Dispose of objects which you did not create. So you should not dispose your context in any of the classes you provided to begin with.
You should however call context.Dispose()
in class, where you actually create this particular instance. And when you do - there should be no other object using it. What you are trying to do is to avoid design issue you have instead of fixing it. Thats wrong, imho. And that will bite you back at some point, when you'll forget to put yet another null check somewhere.
Using the code you provided the example might look like:
void SomeMethodInOuterScope()
{
var context = new DataEntities();
var test = new Test(context);
try
{
test.InsertRecord(new Person());
...............
}
catch(Exception ex)
{
....
}
finally
{
context.Dispose();
}
}
Here is another example (when context is not local)
class SomeClassInOuterScope : IDisposable
{
private DataEntities _context;
public SomeClassInOuterScope()
{
_context = new DataEntities();
}
public void Test()
{
var test = new Test(_context);
test.InsertRecord(new Person());
...............
}
public void Dispose()
{
_context.Dispose();
}
}
void SomeMethodInOuterOuterScope()
{
var someclass = new SomeClassInOuterScope();
try
{
someclass.Test();
...............
}
catch(Exception ex)
{
....
}
finally
{
someclass.Dispose();
}
}