As a learning process, I tried to implement the UoW with repository patterns and I have the following setup:
public interface IUnitOfWork : IDisposable
{
MyEntities Context { get; set; }
string GetConnectionString()
void Complete();
}
public abstract class RepositoryBase<TEntity> : IRepository<TEntity> where TEntity : class
{
protected MyEntities context;
protected DbSet<TEntity> dbSet;
protected RepositoryBase(IUnitOfWork unitOfWork)
{
context = unitOfWork.Context;
dbSet = context.Set<TEntity>();
}
}
public class ItemRepository : RepositoryBase<Item>, IItemRepository
{
public ItemRepository(IUnitOfWork unitOfWork)
: base(unitOfWork)
{
}
public Item GetById(int id)
{
// return a item
}
}
To actually use the ItemRespoitory, I am doing the following:
using (var unitOfWork = new UnitOfWork())
{
var ItemRepository = new ItemRepository(unitOfWork);
var item = ItemRepository.GetById(1);
}
which works fine, and now I want to do this using IoC/DI with simple injector:
var container = new Container();
container.Register<IUnitOfWork, UnitOfWork>();
container.Register<IItemRepository, ItemRepository>();
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
But now my question is, since I am injecting the ItemRepository to the constructor of a controller
public MyController(IItemRepository itemRepository)
{
_itemRepository = itemRepository;
}
how should I dispose the unit of work when I am done with the repository? because I don't have to create a unitofwork and wrap it in a using statement anymore. Am I doing this correctly? What should the right way of applying DI with UoW and repo patterns in my case? Thanks.