DEV Community

Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Dependency Injection and Inversion of Control (IoC) Containers

Dependency Injection (DI) and Inversion of Control (IoC) are design principles that promote the separation of concerns and improve the testability, maintainability, and flexibility of your code. C# offers various IoC containers and DI frameworks that facilitate managing object dependencies.

Here's an example using the popular IoC container called Autofac:

using System;
using Autofac;

public class Program
{
    public static void Main()
    {
        // Create a container builder
        var containerBuilder = new ContainerBuilder();

        // Register dependencies with the container
        containerBuilder.RegisterType<Logger>().As<ILogger>();
        containerBuilder.RegisterType<EmailService>().As<IMailService>();

        // Build the container
        var container = containerBuilder.Build();

        // Resolve and use dependencies
        using (var scope = container.BeginLifetimeScope())
        {
            var logger = scope.Resolve<ILogger>();
            var mailService = scope.Resolve<IMailService>();

            var app = new Application(logger, mailService);
            app.Run();
        }
    }
}

public interface ILogger
{
    void Log(string message);
}

public class Logger : ILogger
{
    public void Log(string message)
    {
        Console.WriteLine($"Logging: {message}");
    }
}

public interface IMailService
{
    void SendMail(string to, string subject, string body);
}

public class EmailService : IMailService
{
    public void SendMail(string to, string subject, string body)
    {
        Console.WriteLine($"Sending email to {to}, Subject: {subject}, Body: {body}");
    }
}

public class Application
{
    private readonly ILogger _logger;
    private readonly IMailService _mailService;

    public Application(ILogger logger, IMailService mailService)
    {
        _logger = logger;
        _mailService = mailService;
    }

    public void Run()
    {
        _logger.Log("Application started.");
        _mailService.SendMail("user@example.com", "Hello", "Welcome to our app!");
        _logger.Log("Application finished.");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We use Autofac to create a container that manages the dependencies for the Application class.
  • We register Logger and EmailService as implementations for the ILogger and IMailService interfaces.
  • In the Application class, we inject the dependencies through its constructor.
  • We resolve the dependencies within a container scope and use them to run the application.

IoC containers like Autofac simplify the management of dependencies in complex applications, promoting modularity and testability. They also support various features like object lifetime management and automatic resolution of dependencies, making it easier to build scalable and maintainable applications.

Top comments (0)