Overriding Existing Methods

REN’s Unit of Work and Repository system is designed for extensibility and customization. All major methods are marked as virtual—allowing you to override and tailor database behavior for your project’s unique needs.


How to Override?

1. Create a New Service to Override Existing Method

You can create your own custom Unit of Work by inheriting from RENUnitOfWork and overriding any method as needed. For example, to add custom logging to transaction operations:

public class OverridedRENUnitOfWork<TDbContext>(TDbContext context) 
    : RENUnitOfWork<TDbContext>(context), 
    IRENUnitOfWork<TDbContext> where TDbContext : DbContext
{
    public override IRENRepository<TEntity>? GetRepository<TEntity>()
    {
        Console.WriteLine("OverridedRENUnitOfWork GetRENRepository called");
        // You can add custom logic here before calling the base method
        return base.GetRepository<TEntity>();
    }
}

2. Register Your Custom Implementation

In your Program.cs, register your custom Unit of Work using the generic registration method:

builder.Services.RegisterRENDataServices(unitOfWorkOpenType: typeof(OverridedRENUnitOfWork<>));

In this example, OverridedRENUnitOfWork<RenDbContext> is your custom class that inherits from RENUnitOfWork<RenDbContext>. The DI container will now use your class for all Unit of Work operations.

How Does the Registration Work?

public static IServiceCollection RegisterRENDataServices(this IServiceCollection services, Type unitOfWorkOpenType)
{
    services.AddScoped(typeof(IRENUnitOfWork<>), unitOfWorkOpenType);

    return services;
}

If you register your custom class, it will be used for all database operations via the IRENUnitOfWork<> interface. If you want to revert to the default, just switch the registration back!

Pro Tip:


3. Use Custom Service In Action

[Route("api/[controller]")]
[ApiController]
public class OverridedDataController(IRENUnitOfWork<RenDbContext> unitOfWork) : ControllerBase
{
    [HttpGet("get-repository")]
    public IActionResult GetRepository(string key)
    {
        var employeeRepository = unitOfWork.GetRepository<Employee>();
        return Ok(employeeRepository.GetList());
    }
}

And you’re good to go!

Last updated