Sobes.tech
Back to questions
Junior — Middle
61

Могли бы вы показать пример использования контейнера依赖注Injection в проекте?

Answer from AI

sobes.tech AI

Пример использования контейнера внедрения зависимостей (Dependency Injection) в C# с помощью встроенного в .NET Core механизма:

// Интерфейс сервиса
public interface IMessageService
{
    void Send(string message);
}

// Реализация сервиса
public class EmailMessageService : IMessageService
{
    public void Send(string message)
    {
        Console.WriteLine($"Отправка email: {message}");
    }
}

// Класс, который зависит от IMessageService
public class NotificationManager
{
    private readonly IMessageService _messageService;

    // Зависимость внедряется через конструктор
    public NotificationManager(IMessageService messageService)
    {
        _messageService = messageService;
    }

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

// Настройка DI контейнера в приложении
var services = new ServiceCollection();
services.AddTransient<IMessageService, EmailMessageService>();
services.AddTransient<NotificationManager>();

var serviceProvider = services.BuildServiceProvider();

// Получение экземпляра NotificationManager с внедренной зависимостью
var notifier = serviceProvider.GetService<NotificationManager>();
notifier.Notify("Привет, Dependency Injection!");

В этом примере интерфейс IMessageService реализуется классом EmailMessageService. Класс NotificationManager получает зависимость через конструктор. DI контейнер (.NET Core ServiceCollection) настраивается для связывания интерфейса с реализацией и создания экземпляров с внедрением зависимостей автоматически.