Achieving Dependency Injection in .NET Core WebAPI

.NET Core Web API

Introduction

In a .NET Core Web API application, you can achieve Dependency Injection (DI) by registering and injecting services into your controllers or other parts of your application. DI is essential in a Web API to manage the dependencies and promote modularity and testability. Here's how you can use DI in a .NET Core Web API.

Steps to achieve dependency injection in .Net Core WebAPI

Step 1. In Dependency Injection (DI), interfaces and classes play distinct roles, and they are used for different purposes in the .Net core.

1. Interface

Interfaces define contracts or blueprints for classes. They specify a set of methods, properties, or events that implementing classes must adhere to. In DI, interfaces are commonly used to define the contract for services or dependencies that your application relies.

  • create  Interface “IEmployeeInformationRepository.cs” and create getemployeeList functions.
public interface IEmployeeInformationRepository
{
    Task<List<UserInformation>> GetEmployeeList();
}

2. Class

Classes implement interfaces. When you create a class that implements an interface, you are providing the concrete implementation of the methods and properties specified by that interface.

  • Create class “EmployeeInformationRepository.cs”
  • Interface interhit into the class file and all function definitions and logic to implement.
  • getemployeelist function implementations and integrate dbclass functionalities.
public class EmployeeInformationRepository : IEmployeeInformationRepository
{
    private readonly DapperContext _context;

    public EmployeeInformationRepository(DapperContext context)
    {
        _context = context;
    }

    public async Task<List<UserInformation>> GetEmployeeList()
    {
        var query = "select * from UserInformation";

        using (var connection = _context.CreateConnection())
        {
            var list = await connection.QueryAsync<UserInformation>(query);
            return list.ToList();
        }
    }
}

Step 2. Register Dependency injection in the program.cs file.

builder.Services.AddScoped<IEmployeeInformationRepository,EmployeeInformationRepository>();

In service dependency in 3 types of service lifetime.

  1. Singleton: One instance for the entire application's lifetime.
  2. Transient: A new instance every time it's requested
  3. Scoped: One instance per scope

Step 3. Inject the Dependency into the Controller Level

Create Employee Controller

public class EmployeeController : ControllerBase
{
    private readonly IEmployeeInformationRepository _employeeinformation;

    public EmployeeController(IEmployeeInformationRepository employeeInformationRepository)
    {
        _employeeinformation = employeeInformationRepository;
    }

    [HttpGet("List")]
    public async Task<ActionResult> GetAllEmployee()
    {
        try
        {
            var employeeList = await _employeeinformation.GetEmployeeList();
            return new CreatedResult(string.Empty, new { Code = 200, Status = true, Message = "", Data = employeeList });
        }
        catch (Exception ex)
        {
            return StatusCode(500, ex.Message);
        }
    }
}

Here, we inject IEmployeeInformationRepository into the EmployeeController constructor. The DI container will automatically provide an instance of EmployeeInformationRepository when the controller is created.

Step 4. Test your API

Run your WebAPI, and when you make a GET request to /api/Employee/List, it will return db fetch data which is provided by the injected service.

Get Request

In program.cs don’t configure dependency lifetime. This type of error is thrown.

Configure Dependency

Conclusion

That's it! You have successfully implemented dependency injection in a .NET Core WebAPI project, which promotes loose coupling, maintainability, and testability of your application.

Happy learning and happy coding to your tool.

May your coding journey be filled with curiosity, creativity, and continuous growth. Remember that every challenge you encounter is an opportunity to learn and improve. Stay inspired, stay persistent, and enjoy the thrill of solving problems and building amazing software. If you ever have questions or need assistance along the way, don't hesitate to reach out. Happy coding!


Similar Articles