Having a repository dependent on another repository

Repository should have single responsibility – persist one kind of entity. E.g. employees. If you have to delete some associated records from other repository, it looks like business logic. E.g.

When employee is fired we should remove his work log

And usual place for business logic is a domain services. This service will have both repositories and do all the job:


Implementation will look like

public class StaffService
    private IEmployeeRepository employeeRepository;
    private IWorkLogRepository workLogRepository;
    private IUnitOfWorkFactory uowFactory;

    // inject dependencies

    public void Fire(Employee employee)
        using(var uow = uowFactory.SartNew())

So, basic advises

  • try to keep your business logic in one place, do not spread part of it to UI, part of it to repositories, part to database (sometimes due to performance issues you have to do some logic on database side, but thats an exception)
  • never let repositories reference other repositories, repository is a very low-level component of your application with very simple responsibilities

You may wonder what to do if you have employee and it has some nested object which is stored in different database table. If you use that object separately from employee, then everything is as above – you should have separate repository, and some other object (service) which manipulates both repositories. But if you don’t use that nested object separately from employee, then employee is an Aggregate Root and you should have only employee repository, which will query both tables inside.

Leave a Comment