Overriding Existing Methods

REN’s Repository service is designed for extensibility and customization. All major methods are marked as virtual on source code, allowing you to override and tailor data access behavior to your project’s needs.


How to Override?

1. Create a Custom Repository Class

Simply create your own repository by inheriting from RENRepository<TEntity>, then override any method to add custom behavior. For example, you might add extra logging, validation, or modify query logic:

public class OverridedRENRepository<TEntity>(RenDbContext context) 
    : RENRepository<TEntity>(context) where TEntity : class
{
    public override TEntity? GetSingle(Expression<Func<TEntity, bool>> filter,
        Func<IQueryable<TEntity>, IQueryable<TEntity>>? include = null,
        bool isReadOnly = false)
    {
        Console.WriteLine("OverridedRENRepository GetSingle called");
        // You can add custom logic here before calling the base method
        return base.GetSingle(filter, include, isReadOnly);
    }

    public override TEntity? Find<TKey>(TKey key)
    {
        Console.WriteLine("OverridedRENRepository Find called with key: " + key);
        // You can add custom logic here before calling the base method
        return base.Find(key);
    }
}

2. Register Your Custom Repository

Although you define and register your custom repository and its interface, the recommended approach in REN.Kit is not to inject repositories directly. Instead, always access your repositories through the Unit of Work instance.

This ensures all your data operations—queries, updates, transactions—are tracked, coordinated, and committed consistently.

When requesting a repository from your Unit of Work, specify your custom repository type using the generic overload:

private readonly IRENRepository<Employee> customEmployeeRepository = unitOfWork.GetRepository<OverridedRENRepository<Employee>, Employee>();

This approach ensures that your custom implementation is used for all data access operations involving the specified entity type.


3. Use the Custom Repository in Your Application

[Route("api/[controller]")]
[ApiController]
public class OverridedRepositoryDataController(IRENUnitOfWork<RenDbContext> unitOfWork) : ControllerBase
{
    private readonly IRENRepository<Employee> customEmployeeRepository = unitOfWork.GetRepository<OverridedRENRepository<Employee>, Employee>();

    [HttpGet("find")]
    public IActionResult GetRepository(Guid key)
    {
        var employee = customEmployeeRepository.Find(key);
        if (employee == null)
        {
            return NotFound();
        }
        return Ok(employee);
    }
}

Pro Tip

Last updated