Dependency Injection Container for C# (.NET): Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Dependency Injection Container for C# (.NET): Complete Guide



Dependency Injection (DI) is one of the key design patterns in modern C# and .NET development. It allows you to create loosely coupled, testable, and easily maintainable applications. In this article, we will take a detailed look at what a Dependency Injection container is, how to use it in .NET, and provide practical code examples.



What is Dependency Injection?



Dependency Injection is a pattern where an object receives its dependencies from the outside, rather than creating them itself. This allows you to:

  • Reduce coupling between components
  • Simplify testing (ability to replace dependencies with mocks)
  • Increase code flexibility and reusability
  • Centralize object lifecycle management


What is a DI Container?



A DI container (or IoC container) is a library that automates the dependency injection process. It takes responsibility for creating objects and managing their lifetimes. In .NET, the primary DI container is Microsoft.Extensions.DependencyInjection, which is built into ASP.NET Core and can be used in any .NET application.



Key Concepts of a DI Container



A DI container operates with the following concepts:

  • Service Registration — the process of adding types and their implementations to the container
  • Dependency Resolution — automatic creation of objects with their dependencies
  • Service Lifetime — determines how long an object exists (Transient, Scoped, Singleton)


Setting Up a DI Container in .NET



To get started with a DI container, you need to install the Microsoft.Extensions.DependencyInjection package. This can be done via NuGet:



dotnet add package Microsoft.Extensions.DependencyInjection


After installation, a ServiceCollection instance is created, in which all dependencies are registered:



using Microsoft.Extensions.DependencyInjection;

// Create a service collectionvar services = new ServiceCollection();

// Register servicesservices.AddTransient<ILogger, ConsoleLogger>();services.AddScoped<IUserRepository, UserRepository>();services.AddSingleton<IConfiguration, AppConfiguration>();

// Build the service providervar serviceProvider = services.BuildServiceProvider();


Example of Using a DI Container



Let's consider a real example: a user management application. We'll create interfaces and their implementations:



public interface IUserRepository{    User GetUser(int id);}

public interface IEmailService{ void SendEmail(string to, string subject);}

public class UserRepository : IUserRepository{ public User GetUser(int id) { // Logic to get user from DB return new User { Id = id, Name = "John Doe" }; }}

public class EmailService : IEmailService{ public void SendEmail(string to, string subject) { Console.WriteLine($"Email sent to {to}: {subject}"); }}


Now let's create a UserService class that uses these dependencies:



public class UserService{    private readonly IUserRepository _userRepository;    private readonly IEmailService _emailService;

public UserService(IUserRepository userRepository, IEmailService emailService) { _userRepository = userRepository; _emailService = emailService; }

public void NotifyUser(int userId) { var user = _userRepository.GetUser(userId); _emailService.SendEmail(user.Email, "Welcome!"); }}


Register everything in the DI container

Recommendations