views:

183

answers:

1

I've found lots of examples of the repository pattern, all of which show the repository managing it's own connection lifecycle. I was wondering how people deal with a case where they want to share a single connection across multiple repositories?

The main reason I'm asking is because when I create a transaction, using TransactionScope, I don't really want it to escalate to an DTC transaction. It seems a bit heavyweight, though simple to setup.

What I was thinking was using something similar to the TransactionScope, that would manage a connection lifecycle. However, it seems that is linking the data access to the business process a little. An example of what I mean is:

//As DataScope will handle connections, then repositories will be created from them
//in order to share the connection.
using(DataScope scope = new DataScope())
{
   scope.GetRepository<CustomerRepository>.FindById(10)
}
+1  A: 

When creating a repository, I pass the connection / unitofwork / ISession (nhibernate) that I want to use, in the constructor of the repository.

The repository should not be responsible for creating the connection / ISession itself, since the repository has no knowledge of the context in which it will be used. You could also opt for using an inversion of control container like Castle or Spring.NET.

Frederik Gheysels