Sobes.tech
Junior — Middle

Could you show an example of using the dependency injection container in a project?

sobes.tech AI

Answer from AI

Example of using Dependency Injection container in C# with the built-in .NET Core mechanism:

// Service interface
public interface IMessageService
{
    void Send(string message);
}

// Service implementation
public class EmailMessageService : IMessageService
{
    public void Send(string message)
    {
        Console.WriteLine($"Sending email: {message}");
    }
}

// Class depending on IMessageService
public class NotificationManager
{
    private readonly IMessageService _messageService;

    // Dependency is injected via constructor
    public NotificationManager(IMessageService messageService)
    {
        _messageService = messageService;
    }

    public void Notify(string message)
    {
        _messageService.Send(message);
    }
}

// DI container setup in the application
var services = new ServiceCollection();
services.AddTransient<IMessageService, EmailMessageService>();
services.AddTransient<NotificationManager>();

var serviceProvider = services.BuildServiceProvider();

// Getting an instance of NotificationManager with injected dependency
var notifier = serviceProvider.GetService<NotificationManager>();
notifier.Notify("Hello, Dependency Injection!");

In this example, the IMessageService interface is implemented by the EmailMessageService class. The NotificationManager class receives its dependency through the constructor. The DI container (.NET Core's ServiceCollection) is configured to bind the interface to its implementation and to create instances with dependencies injected automatically.