Reputation: 14161
Below is my code:
using (pgsqlConnection conn = new pgsqlConnection(connStr))
{
} //automatically Dispose()
public class v2Connection:IDisposable
{
public void Dispose()
{
//close the connection and release resources
}
}
This is what I have written so far in my Connection class (v2Connection). It is giving error on pgsqlConnection and it is obvious that at present neither I have a class with this name nor an Interface.
I want to add two function: Open and Close. I am not following where should I call Open() and Close()? If I create an interface with the name: IConnection with two methods:
int Open();
int Close();
How to use this interface in the above code?
Upvotes: 0
Views: 219
Reputation: 2293
You could have a wrapper for your connection :
using (MyConnectionWrapper conn = new MyConnectionWrapper ())
{
}
With MyConnectionWrapper :
public class MyConnectionWrapper : IDisposable
{
void OpenConnection();
void CloseConnection();
void Dispose();
}
and in the constructor of your class
public MyConnectionWrapper ()
{
OpenConnection();
}
and in the Dispose function :
public void Dispose()
{
CloseConnection();
}
Upvotes: 2
Reputation: 6617
The class pgsqlConnection
must implement IDisposable interface. This is what the using statement is doing actually, calls the Dispose method automatically.
Upvotes: 1
Reputation: 54158
I would follow the pattern used in existing SqlConnection
classes - Open
and Close
can be called on any valid instance (given valid state for those ops of course) but Dispose
will Close
the connection if it's not explicitly done in your code on an Open
-ed conection.
using
is really orthogonal to this - it's a nicety in the language to ease your task in ensuring underlying unmanaged resources do not get leaked for IDisposable
objects. In your case, that is essential if the instance is Open
when it goes out of scope, and encapsulating the instance via using
supplies the required Dispose()
call at the right time.
Upvotes: 4