I just have a question related to "best practice". If this question isn't constructive, then just vote it down :)
I had a discussion with a colleague some days ago, we have two completely different philosophies when it comes to best practice regarding open connections to a web service, COM-object, database etc.
I prefer wrapping the connection code in a class that implements IDisposable and let that handle all that comes to connection etc. A short example.
public class APIWrapper : IDiposable
{
public APIWrapper(...)
{
DataHolder = new DataHolder(...);
/// Other init methods
Connect();
}
public [Webservice/Database/COM/etc.] DataHolder { get; private set; }
public void Connect()
{
DataHolder.Connect(...);
}
public void Disconnect()
{
DateHolder.Disconnect();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if(disposing)
{
if (DataHolder != null)
{
Disconnect();
DataHolder = null;
}
}
}
}
And I will use it like this in my Data controller.
public class UserController
{
....
public IList<User> getUsers()
{
using(APIWrapper datalayer = new APIWrapper(...))
{
var users = datalayer.DataHolder.GetUsers();
/// Map users to my enity of users
return mappedUsers;
}
}
}
And my colleagues would look like this:
public class UserController
{
protected [Webservice/Database/COM/etc.] DataHolder { get; set; }
public UserController()
{
DataHolder = new DataHolder(...);
DataHolder.Connect(...);
}
public IList<User> getUsers()
{
var users = DataHolder.GetUsers();
/// Map users to my enity of users
return mappedUsers;
}
/// Who should call this?
public void Dispose()
{
DataHolder.Disconnect();
}
}
The code above are just examples that are simplified (and written i stackoverflow text editor), but I think they show the necessary philosophies.
So, the first example will open and close to connection at each call. The second example will hold the connection open for a longer amount of time.
What is "generally" best practice in your opinion?