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

C# : How can we access private method outside class

Introduction In object-oriented programming, encapsulation is a fundamental principle that restricts direct access to the internal implementation details of a class. Private methods, being part of this internal implementation, are designed to be accessible only within the confines of the class they belong to. However, there might be scenarios where you need to access a private method from outside the class. In this blog post, we'll explore several techniques to achieve this in C#. 1. Reflection: A Powerful Yet Delicate Approach Reflection is a mechanism in C# that allows inspecting and interacting with metadata about types, fields, properties, and methods. While it provides a way to access private methods, it should be used cautiously due to its potential impact on maintainability and performance. using System ; using System . Reflection ; public class MyClass { private void PrivateMethod ( ) { Console . WriteLine ( "This is a private method."...

20+ LINQ Concepts with .Net Code

LINQ   (Language Integrated Query) is one of the most powerful features in .NET, providing a unified syntax to query collections, databases, XML, and other data sources. Below are 20+ important LINQ concepts, their explanations, and code snippets to help you understand their usage. 1.  Where  (Filtering) The  Where()  method is used to filter a collection based on a given condition. var numbers = new List < int > { 1 , 2 , 3 , 4 , 5 , 6 } ; var evenNumbers = numbers . Where ( n => n % 2 == 0 ) . ToList ( ) ; // Output: [2, 4, 6] C# Copy 2.  Select  (Projection) The  Select()  method projects each element of a sequence into a new form, allowing transformation of data. var employees = new List < Employee > { /* ... */ } ; var employeeNames = employees . Select ( e => e . Name ) . ToList ( ) ; // Output: List of employee names C# Copy 3.  OrderBy  (Sorting in Ascending Order) The  Or...

C# : Understanding Types of Classes

In C#, classes serve as the building blocks of object-oriented programming, providing a blueprint for creating objects. Understanding the types of classes and their applications is crucial for designing robust and maintainable software. In this blog, we’ll delve into various types of classes in C#, accompanied by real-world scenarios and code snippets for a practical understanding. 1. Regular (Instance) Classes Definition: Regular classes are the most common type and are used to create instances or objects. They can contain fields, properties, methods, and other members. Example Scenario: A Person class representing individual persons with properties like Name and Age. public class Person { public string Name { get ; set ; } public int Age { get ; set ; } } 2. Static Classes Definition: A static class cannot be instantiated and can only contain static members (methods, properties, fields). It’s often used for utility functions. Example Scenario: A MathUtility cla...