2024-05-13 02:01:32 +04:00

95 lines
2.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftPlantContracts.DependencyInjections
{
/// <summary>
/// Реализация интерфейса установки зависимости между элементами
/// </summary>
public class ServiceDependencyContainer : IDependencyContainer
{
/// <summary>
/// Провайдер сервисов для разрешения зависимостей
/// </summary>
private ServiceProvider? _serviceProvider;
/// <summary>
/// Коллекция сервисов для регистрации зависимостей
/// </summary>
private readonly ServiceCollection _serviceCollection;
/// <summary>
/// Конструктор
/// </summary>
public ServiceDependencyContainer()
{
_serviceCollection = new ServiceCollection();
}
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
public void AddLogging(Action<ILoggingBuilder> configure)
{
_serviceCollection.AddLogging(configure);
}
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
/// <param name="isSingle"></param>
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T, U>();
}
else
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="isSingle"></param>
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T>();
}
else
{
_serviceCollection.AddTransient<T>();
}
_serviceProvider = null;
}
/// <summary>
/// Получение класса со всеми зависимостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T Resolve<T>()
{
if (_serviceProvider == null)
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider.GetService<T>()!;
}
}
}