The PetaPoco.Database object implements IDisposable but I rarely if ever see code samples (including on PetaPoco's own website) that include a using statement as follows:
using (var db = new Database("MyConnectionString"))
{
// Do database stuff
}
Most often I simply see:
var db = new Database("MyConnectionString");
// Do database stuff
// I never see .Dispose() called.
How should PetaPoco.Database objects actually be handed?
If you access unmanaged resources (e.g. files, database connections etc.) in a class, you should implement IDisposable and overwrite the Dispose method to allow you to control when the memory is freed.
The using declaration calls the Dispose method on the object in the correct way when it goes out of scope. The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned.
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
As a simple rule: if a class implements IDisposable then go ahead and wrap it in a using. They may not actually be using any unmanaged resources, but it won't hurt and might future-proof you against changes.
PetaPoco maintainer here. Dispose is the same as calling CloseSharedConnection()
. However, c# syntax only supports using(...) with IDisposable
. For instance IDBConnection
, from memory, supports both Close
and Dispose
.
Basically, it boils down to choice
Example 1
using(var db = new PetaPoco())
{
// some code
}
Example 2
var db = new PetaPoco()
try
{
// code
}
finally
{
db.CloseSharedConnection();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With