Implementing Additional Methods

Surely you should be able to implement new functions addition to existing one if you need it. This is SOLID after all! Let's see how we can do this. First you need to create the interface that inherits from IRENUnitOfWork interface. Your new interface should contain additional methods and must be inherited from IRENUnitOfWork interface to get all function signatures:

public interface IMyUnitOfWork<TDbContext>: IRENUnitOfWork<TDbContext> where TDbContext : RENDbContext
{
    Task MyCustomFunction(CancellationToken cancellationToken = default);
}

Then create your custom UnitOfWork class and make it inherit from RENUnitOfWork class and your new interface (in this case it is IMyUnitOfWork) that contains your custom function signature.

public class MyUnitOfWork<TDbContext> : RENUnitOfWork<TDbContext>, IMyUnitOfWork<TDbContext> where TDbContext : RENDbContext
{
    public MyUnitOfWork(TDbContext context) : base(context) { }

    public Task MyCustomFunction(CancellationToken cancellationToken = default)
    {
        return Task.Factory.StartNew(() =>
        {
            cancellationToken.ThrowIfCancellationRequested();
            Console.WriteLine("This is my custom Function");
            // other custom implementations!

        }, cancellationToken);
    }
}

Then you have to change your register type in Program.cs to this since you will want to use IMyUnitOfWork from now on:

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

Then you can use this custom function as follows:

public class HomeController : ControllerBase
{
    private readonly IMyUnitOfWork<RENDbContext> _uow;

    public HomeController(IMyUnitOfWork<RENDbContext> uow)
    {
        _uow = uow;
    }

    [HttpGet, Route("Index")]
    public async Task<IActionResult> Index()
    {
        await _uow.MyCustomFunction();
        return Ok();
    }   
}

Last updated