I have the following ADO .Net Repository
public class Repository : IRepository, IDisposable
{
private readonly IUnitOfWork UnitOfWork;
private SqlConnection Connection;
public Repository(IUnitOfWork unitOfWork, connectionString)
{
UnitOfWork = unitOfWork;
Connection = new SqlConnection(connectionString);
Connection.Open();
}
public MyObject FindBy(string userName)
{
//...Ado .Net command.ExecuteReader, etc.
}
}
This repository is injected with an IoC container to a Domain Service and is used like so:
public class UserDomainService : IUserDomainService
{
private readonly IRepository Repository;
public UserDomainService(IRepository repository)
{
Repository = repository;
}
public User CreateNewUser(User user)
{
using(Repository)
{
var user = Repository.FindBy(user.UserName);
if(user != null)
throw new Exception("User name already exists!");
Repository.Add(user);
Repository.Commit();
}
}
}
The idea is that I always put the Repository object in a using statement so when it finishes, the connection is closed and disposed of but I see it as a problem since the Domain Service class is still alive and if there is a second call to it, it will fail since the repository has already been destroyed.
Now I have full control of all the code and I want to design only coarse grain service calls, but there's something about the whole thing that doesn't feel right.
I am doing it like this so I can avoid that the Domain Service knows about OpenConnection and CloseConnection methods in the repository.
Is this design inherently bad or is there a better way of doing this?
After thought: All the dependency tree is being generated at the WCF level when a request arrives and, of course you can see that the connection is opened at that moment since it happens in the repository's constructor so I believe that it is not that bad since it is open only for the duration of this particular call. Am I right on this assumption or am I doing something terribly bad by opening the DB connection so early in the process?