DDD Auditing? Domain Layer or Repository Layer?

Viewed 4112

The application I'm currently working on requires every change made to the database be audited in another table:

ex: Employee Table has EmployeeAuditTable

I've been debating on where I should put the auditing functionality! Following DDD, could anyone offer me their advice and opinion?

The options that come to mind to me are the following

  1. When a "Repository" calls save changes, I should perform the auditing logic from the repository (Is this bad design/practice to have the Repository not only persist changes but also persist auditing details as well? Is it even good practice to have a service being called from within a repository (IAuditService in this case))?

Example 1:

public class EmployeeRepository : IRepository
{
    DbContext _db;
    IAuditService _auditService;

    EmployeeRepository(IAuditService auditService)
    {
      _auditService = auditService
    }
    void Update(Employee empl)
    {
        // Update Employee with dbcontext entity framework
        
        // Perform Audit using AuditService
    }

   void SaveChanges()
   {
      // Call save changes on dbcontext
   }
}
  1. Should I call IAuditService within my application services

Example 2:

public class EmployeeService
{
   IAuditService _auditService;
   IUnitOfWork   _unitOfWork;
   IEmployeeRepository _repository;
  
   EmployeeService(IAuditService auditService, IUnitOfWork  unitOfWork, IEmployeeRepository repo)
   {
       _auditService = auditService;
       _unitOfWork= unitOfWork;
       _repo  = repo;
   }

   void UpdateEmployee(int id, string name, int age)
   {
      // Get Employee

      // Update Employee

      // Audit Changes

      // Commit Transaction      
   }
}
3 Answers
Related