Overriding Existing Methods

As you can see in standard implementation, all methods are marked as virtual which means you can customize their content via overriding them.

You can override the existing methods to create a new class. To do that, newly created classes should inherit from RENRepository class:

public class MyRepository<TEntity> : RENRepository<TEntity> where TEntity : class
{
    public MyRepository(RENDbContext context) : base(context) { }

    public override Task<TEntity?> GetSingleAsync(Expression<Func<TEntity, bool>> filter,
        Expression<Func<IQueryable<TEntity>, IQueryable<TEntity>>>? include = null,
        bool isReadOnly = false,
        CancellationToken cancellationToken = default)
    {
        Console.WriteLine("Getting......");
        // Custom implementations
        return base.GetSingleAsync(filter, null, include, isReadOnly, cancellationToken);
    }
}

Here, we overrided the existing method to expand it's functionality. From now on, we don't have register MyRepository in Program.cs since we will use it in our UnitOfWork class.

In Program.cs you must register it with IRENUnitOfWork since we are not using custom Interface here:

builder.Services.AddScoped(typeof(IRENUnitOfWork<>), typeof(MyUnitOfWork<>));

To achieve this we can create new function named GetMyRepository in our UnitOfWork:

public class MyUnitOfWork<TDbContext> : RENUnitOfWork<TDbContext> where TDbContext : RENDbContext
{
    public MyUnitOfWork(TDbContext context) : base(context) { }
    
    public override IRENRepository<TEntity>? GetRENRepository<TEntity>()
    {
        return (IRENRepository<TEntity>?)Activator.CreateInstance(typeof(MyRepository<TEntity>), new object[] { _context });
    }
}

From now on GetMyRepository function returns IMyRepository object which contains our custom implementation.

You can implement custom function instead of overriding existing one to get repository and use it. It is all up to you!

And you can get and use your custom repository like this:

public class HomeController : ControllerBase
{
    private readonly IRENUnitOfWork<RENDbContext> _uow;
    private readonly IRENRepository<Side> _customSideRepository;
    
    public HomeController(IRENUnitOfWork<RENDbContext> uow)
    {
        _uow = uow;
        _customSideRepository = _uow.GetRENRepository<Side>();
    }
    
    [HttpGet, Route("Index")]
    public async Task<IActionResult> Index()
    {
        var side = await _customSideRepository.GetSingleAsync(_=>_.Id == 1);
        return Ok(side);
    }
}

Last updated