I am working on a unit of work class and I’m curious how the connection should be handled. My repositories take in a unit of work, and use that connection for Get() commands.
Obviously, Commit() will handle all Add, Updates and Deletes. This would open the connection and begin the transaction and close when finished. How should Gets be handled?
Should the UOW, open the connection in the constructor and close when completely finished? Meaning while I pass UOW from repo to repo, the connection is open. Or should I be opening and closing it only as needed?
Approach #1: Unit of work opens connection and connection remains open until processing is finished?
public UnitOfWork(IDbConnection connection)
{
Connection = connection;
Connection.Open();
Transaction = Connection.BeginTransaction();
}
Approach #2: Snippet of a Get method that opens right before read and closes right after. If passing to multiple repos, same connection is used, just opened and closed a bunch.
using (var reader = manager.GetReader())
{
UOW.Connection.Open();
while (reader.Read())
list.Add(factory.CreateTFromReader(reader));
UOW.Connection.Close();
}
No, you should always open the connection when needed and be absolutely sure to close it when the work is complete. The Connection Pooling mechanism will take care of keeping the connection available for your current user or for other users connecting concurrently on the same server
I think also that the second example is not quite right. You should have something like this
This will ensure that the connection is closed even in the event of exceptions, and that is returned to the pool in order to be reused
Connection Pooling