The connection will be managed automatically. However, there are (or at least can be as the comments suggest) additional resouces associated with the DataContext. These resources will not be released until the DataContext is destroyed by the garbage collector. So, it is usually better to make sure that dispose is called when you don't need the DataContext anymore.
using (ProjDataContext db = new ProjDataContext()) {
bool hasPassword = (from p in db.tblSpecUser
where p.UserID == userId
select p.HasPassword).FirstOrDefault();
return hasPassword;
}
Here it is ensured that db.Dispose()
is called when the using block exits, thus closing the connection explicitly.
Edit: Following the discussion I looked at the DataContext dispose myself (also using Reflector) and found the following code (FW 3.5) which gets called from DataContext.Dispose
:
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.provider != null)
{
this.provider.Dispose();
this.provider = null;
}
this.services = null;
this.tables = null;
this.loadOptions = null;
}
}
So there are resources that gets freed:
- The provider which may hold a
DbConnection
, a log (TextWriter
) and a DbTransaction
.
- The the
CommonDataServices
.
- The tables dictionary.
- The
LoadOptions
.
The provider may hold resources that needs to be disposed (DbConnection
and DbTransaction
). Also the TextWriter
for the log may have to be disposed, depending upon what instance of the TextWriter
the user has assigned to the DataContext
's logging mechanism, e.g. a FileWriter that then gets closed automatically.
The other properties hold, as far as I understand them -without looking too much into detail - only memory, but this is also made available for garbage collection by the dispose method, however, the it is not determined when the memory actually gets freed.
So, finally I totally agree with casparOne's statement:
In general, sharing data-access resources like this is a bad idea.
You should create your resources to access the DB, perform your operations, and then dispose of them when done.