Skip to main content

Dependency Injection (DI) in .NET Core with an Item API

 

Dependency Injection (DI) is a design pattern that allows for better separation of concerns, easier testing, and more maintainable code by injecting dependencies into classes rather than hard-coding them. .NET Core has built-in support for DI, making it an integral part of building scalable and flexible applications.

In this blog, we'll explore DI in .NET Core using an Item API as an example. We'll walk through the process of setting up DI in a .NET Core application and demonstrate how it can be used to manage dependencies.

What is Dependency Injection?

Dependency Injection is a technique where an object receives other objects (dependencies) it needs, rather than creating them itself. This approach allows for better flexibility and easier testing, as dependencies can be swapped out or mocked as needed.

In .NET Core, DI is supported natively and is typically configured in the Startup.cs file, where services are registered and managed by the built-in IoC (Inversion of Control) container.

Benefits of Dependency Injection

  1. Loose Coupling: Classes are not tightly bound to their dependencies, making them easier to manage and extend.
  2. Easier Testing: Dependencies can be mocked or replaced during testing, enabling unit tests to focus on the class under test.
  3. Improved Maintainability: By following the DI pattern, your code becomes more modular and easier to refactor.

Implementing Dependency Injection in an Item API

Let's dive into the implementation of DI in a simple Item API.

1. Creating the Item Repository Interface

First, let's create an interface that defines the operations related to items. This interface will serve as a contract that the repository class will implement.

public interface IItemRepository
{
    IEnumerable<Item> GetAllItems();
    Item GetItemById(int id);
    void AddItem(Item item);
    void UpdateItem(Item item);
    void DeleteItem(int id);
}

The IItemRepository interface defines methods for retrieving, adding, updating, and deleting items.

2. Implementing the Item Repository

Next, we'll create a concrete implementation of the IItemRepository interface. This class will handle the data operations.

public class ItemRepository : IItemRepository
{
    private readonly List<Item> _items = new List<Item>
    {
        new Item { Id = 1, Name = "Item1", Description = "First item" },
        new Item { Id = 2, Name = "Item2", Description = "Second item" },
    };

    public IEnumerable<Item> GetAllItems()
    {
        return _items;
    }

    public Item GetItemById(int id)
    {
        return _items.FirstOrDefault(i => i.Id == id);
    }

    public void AddItem(Item item)
    {
        item.Id = _items.Max(i => i.Id) + 1;
        _items.Add(item);
    }

    public void UpdateItem(Item item)
    {
        var existingItem = GetItemById(item.Id);
        if (existingItem != null)
        {
            existingItem.Name = item.Name;
            existingItem.Description = item.Description;
        }
    }

    public void DeleteItem(int id)
    {
        var item = GetItemById(id);
        if (item != null)
        {
            _items.Remove(item);
        }
    }
}

The ItemRepository class provides the actual implementation of the CRUD operations defined in the IItemRepository interface.

3. Registering the Repository in the Dependency Injection Container

To use DI, we need to register the ItemRepository as a service in the DI container. This is typically done in the Startup.cs file.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        // Register the ItemRepository with the DI container
        services.AddScoped<IItemRepository, ItemRepository>();
    }

    // Other methods...
}

Here, AddScoped is used to register the ItemRepository as a scoped service. This means a new instance of the repository will be created per request. Other lifetimes include Transient (a new instance is created every time it’s requested) and Singleton (a single instance is used throughout the application).

4. Injecting the Repository into the Controller

Now that the repository is registered, we can inject it into the ItemsController using constructor injection.

[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
    private readonly IItemRepository _itemRepository;

    public ItemsController(IItemRepository itemRepository)
    {
        _itemRepository = itemRepository;
    }

    [HttpGet]
    public ActionResult<IEnumerable<Item>> GetItems()
    {
        return Ok(_itemRepository.GetAllItems());
    }

    [HttpGet("{id}")]
    public ActionResult<Item> GetItem(int id)
    {
        var item = _itemRepository.GetItemById(id);
        if (item == null)
        {
            return NotFound();
        }
        return Ok(item);
    }

    [HttpPost]
    public ActionResult<Item> CreateItem(Item item)
    {
        _itemRepository.AddItem(item);
        return CreatedAtAction(nameof(GetItem), new { id = item.Id }, item);
    }

    [HttpPut("{id}")]
    public ActionResult UpdateItem(int id, Item updatedItem)
    {
        var item = _itemRepository.GetItemById(id);
        if (item == null)
        {
            return NotFound();
        }

        _itemRepository.UpdateItem(updatedItem);

        return NoContent();
    }

    [HttpDelete("{id}")]
    public ActionResult DeleteItem(int id)
    {
        var item = _itemRepository.GetItemById(id);
        if (item == null)
        {
            return NotFound();
        }

        _itemRepository.DeleteItem(id);

        return NoContent();
    }
}

In the ItemsController, the IItemRepository is injected via the constructor. This allows the controller to use the repository for its operations without needing to know the details of the implementation.

Conclusion

Dependency Injection is a powerful feature in .NET Core that promotes loose coupling, enhances testability, and improves maintainability. By following the pattern demonstrated in this blog, you can create a clean, modular, and testable architecture for your applications.

The Item API example highlights how to set up and use DI in a .NET Core application, from defining interfaces to implementing repositories and injecting dependencies into controllers. By embracing DI, your applications will become more flexible and easier to maintain as they grow in complexity.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...