I have the following ADO .Net Repository
public class Repository : IRepository, IDisposable
{
private readonly IUnitOfWork UnitOfWork;
private SqlConnectio
Inject a factory that creates the instances you need, not an instance itself.
Take an IRepositoryFactory
so that you can create an IRepository
and dispose of it each time you use it. This way, neither the domain service or the factory would need to be disposable. Also, and importantly, you keep the code abstract by still injecting the implementation as opposed to hard-coding it.
public class UserDomainService : IUserDomainService
{
private readonly IRepositoryFactory RepositoryFactory;
public UserDomainService(IRepositoryFactory factory)
{
RepositoryFactory = factory;
}
public User CreateNewUser(User user)
{
using (IRepository repository = RepositoryFactory.Create())
{
var user = repository.FindBy(user.UserName);
if(user != null)
throw new Exception("User name already exists!");
repository.Add(user);
repository.Commit();
}
}
}
You don't always have to inject the type you need. On reading up on Castle Windsor (whose mindset is register-resolve-release), you find that if you want to Resolve stuff at an indeterminate time in the app's life, it is suggested to use Type Factories.
You know you will need a Repository, but don't know when. Instead of asking for a repository, ask for something that creates them. The level of abstraction is thus maintained and you have not leaked any implementation.