Reputation: 2904
I have a site which uses a C# class file, and at the top of the file, I have:
JTSEntities database = new JTSEntities();
(an ADO.NET thingy).
I have it right up the top because I don't really feel like writing the same thing over and over again.
But it raises one question... Because it's up the top there, how will it get disposed, and when - and how can I dispose of it (or do I need to) when the user closes the page?
Upvotes: 0
Views: 307
Reputation: 7692
Ok so, based on the type of the attribute, we can say that it's an instance attribute
. This means that this attribute will have the same lifecyle as the object that has it, unless its instance is passed to another object.
If it's protected, then only the owner object and its childs (that is, objects that inherit from this class) will have access to it. If you don't pass it as a reference argument, then we're ok with the first statement: it will be cleaned by the GC as soon as the object is cleaned.
If you just use this object on a regular webform page lifecycle, then you don't have to worry with disposing it. The page lifecycle will do it for you.
Regards
Upvotes: 2
Reputation: 150108
It is bad practice to hold on to anything that wraps a database connection for longer than needed.
The best practice would be to release the database connection as soon as it is no longer needed for the current operation (such as populating initial values, etc.), e.g. something like
using (JTSEntities database = new JTSEntities())
{
// Use database
}
if it implements IDisposable.
If for some reason you must keep it alive for the duration of the page, be sure you call an appropriate method to release resources (.Close(), .Dispose(), etc.) in the page close event handler.
Upvotes: 6
Reputation: 25684
Implement IDisposable
in this class and dispose of this object inside the Dispose()
method. When using this class, make sure you call Dispose when you are done (preferably with a using
block)
Beyond that, you don't need to worry about it.
public class MyClass : IDisposable
{
protected JTSEntities database = new JTSEntities();
public void Dispose()
{
database.Dispose();
}
}
// When calling this class
using(MyClass cls = new MyClass())
{
// Do Stuff
} // Dispose is automatically called here.
Upvotes: 2