Implementing New Methods

Sometimes, your project needs database or transactional operations that go beyond what the standard Unit of Work provides. Thanks to REN.Kit’s extensible design, you can easily add brand new methods to your custom Unit of Work—without touching the underlying implementation!


How to Extend?

1. Create a New Service Interface to Define Your Method

Define an interface that extends the default Unit of Work interface and adds your new method(s):

public interface IExtendedRENUnitOfWork<TDbContext> 
    : IRENUnitOfWork<TDbContext> where TDbContext : DbContext
{
    void AdditionalMethod();
}

This interface introduces your new method(s) while preserving all the default Unit of Work functionality.


2. Create a New Service That Implements Your Interface

Implement your interface by inheriting from RENUnitOfWork<TDbContext> and adding your custom logic:

public class ExtendedRENUnitOfWork<TDbContext>(TDbContext context) 
    : RENUnitOfWork<TDbContext>(context), 
    IExtendedRENUnitOfWork<TDbContext> where TDbContext : DbContext
{
    public void AdditionalMethod()
    {
        Console.WriteLine("ExtendedRENUnitOfWork AdditionalMethod called.");
        // Implement your additional logic here
    }
}

3. Register Your Custom Implementation

Since you’ve created a new interface and class, you should register them like this:

builder.Services.RegisterRENDataServices<IExtendedRENUnitOfWork<RenDbContext>, ExtendedRENUnitOfWork<RenDbContext>>();

This tells REN.Kit’s dependency injection to use your extended version whenever your interface is requested. You can also change the DBContext according to your needs when using one or more contexes!

The registration method looks like:

public static IServiceCollection RegisterRENDataServices<TIRENUnitOfWork, TRENUnitOfWork>(this IServiceCollection services)
{
    services.AddScoped(typeof(TIRENUnitOfWork), typeof(TRENUnitOfWork));

    return services;

4. Use Your Custom Service in Action

Now, you can inject your extended Unit of Work anywhere and use your custom method:

[Route("api/[controller]")]
[ApiController]
public class ExtendedDataController(IExtendedRENUnitOfWork<RenDbContext> unitOfWork) : ControllerBase
{
    [HttpGet("additional-method")]
    public IActionResult AdditionalMethod()
    {
        unitOfWork.AdditionalMethod();
        return Ok("Additional method called successfully.");
    }
}

And you're good to go!

Pro Tip:

Last updated