Dependency Injection (DI) in .NET Core with a Simple Example

Introduction

Dependency Injection (DI) is a fundamental concept in modern software development, promoting the design principle of Inversion of Control (IoC). In the context of .NET Core, DI is a powerful technique that enhances modularity, testability, and maintainability of your code. This article will guide you through the basics of DI in .NET Core with a straightforward example to illustrate its usage.

What is Dependency Injection?

Dependency Injection is a design pattern in which a class receives its dependencies from an external source rather than creating them itself. This approach decouples the implementation from the interface, leading to more modular and testable code. In .NET Core, DI is built into the framework, making it easy to implement.

Setting up a .NET Core console application

Let's start by creating a new .NET Core console application to demonstrate DI.

Create a new .NET Core console application

dotnet new console -n DIExample
cd DIExample

Install the necessary NuGet package

dotnet add package Microsoft.Extensions.DependencyInjection

Creating the Interface and Implementation

First, we need an interface and a class that implements this interface.

IHelloService.cs

public interface IHelloService
{
    void SayHello(string name);
}

HelloService.cs

public class HelloService : IHelloService
{
    public void SayHello(string name)
    {
        Console.WriteLine($"Hello, {name}!");
    }
}

In this example, IHelloService defines a single method SayHello, and HelloService provides the implementation for this method.

Setting up Dependency Injection in Program.cs

Now, let's configure the DI container and use the HelloService in our application.

Program. cs

using Microsoft.Extensions.DependencyInjection;
using System;
class Program
{
    static void Main(string[] args)
    {
        // Create a new ServiceCollection
        var serviceCollection = new ServiceCollection();
        // Register the services
        serviceCollection.AddTransient<IHelloService, HelloService>();
        // Build the ServiceProvider
        var serviceProvider = serviceCollection.BuildServiceProvider();
        // Resolve the service and use it
        var helloService = serviceProvider.GetService<IHelloService>();
        helloService.SayHello("World");
    }
}

Explanation

Service Registration

serviceCollection.AddTransient<IHelloService, HelloService>();

This line registers HelloService as the implementation of the IHelloService interface. AddTransient specifies that a new instance of HelloService will be created each time it is requested. Other lifetimes include AddScoped (one instance per request) and AddSingleton (one instance for the lifetime of the application).

Building the Service Provider

var serviceProvider = serviceCollection.BuildServiceProvider();

This line builds the ServiceProvider, which is responsible for resolving dependencies.

Resolving the Service

var helloService = serviceProvider.GetService<IHelloService>();

This line retrieves an instance of IHelloService from the ServiceProvider, which, thanks to the registration, returns an instance of HelloService.

Using the Service

helloService.SayHello("World");

This line calls the SayHello method on the HelloService instance.

Running the Application

You should see the output.

Hello, World!

Conclusion

This article provided a basic introduction to Dependency Injection in .NET Core. By following this example, you can see how DI helps in decoupling your code, making it more modular, testable, and maintainable. DI is a powerful tool in .NET Core, and understanding its principles is essential for developing robust and scalable applications.

Please consider liking and following me for more articles and if you find this content helpful.


Similar Articles
Citiustech Healthcare Technology Pvt Ltd
CitiusTech plays a deep and meaningful role in powering the future of healthcare.