PIbd-21_RazubaevSM_Plumbing.../PlumbingRepair/PlumbingRepairContracts/DI/ServiceProviderLoader.cs

77 lines
3.0 KiB
C#
Raw Normal View History

2024-05-16 17:00:28 +04:00
using System.Reflection;
namespace PlumbingRepairContracts.DI
{
public class ServiceProviderLoader
{
/// <summary>
/// Загрузка всех классов-реализаций IImplementationExtension
/// </summary>
/// <returns></returns>
public static IImplementationExtension? GetImplementationExtensions()
{
IImplementationExtension? source = null;
var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var file in files.Distinct())
{
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t))
{
if (source == null)
{
source = (IImplementationExtension)Activator.CreateInstance(t)!;
}
else
{
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > source.Priority)
{
source = newSource;
}
}
}
}
}
return source;
}
2024-05-16 18:30:57 +04:00
public static IImplementationBusinessLogicExtension? GetBusinessLogicImplementationExtensions()
{
IImplementationBusinessLogicExtension? source = null;
var files = Directory.GetFiles(TryGetBusinessLogicImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var file in files.Distinct())
{
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IImplementationBusinessLogicExtension).IsAssignableFrom(t))
{
source = (IImplementationBusinessLogicExtension)Activator.CreateInstance(t)!;
break;
}
}
}
return source;
}
private static string TryGetBusinessLogicImplementationExtensionsFolder()
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null && !directory.GetDirectories("BusinessLogicImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "BusinessLogicImplementationExtensions"))
{
directory = directory.Parent;
}
return $"{directory?.FullName}\\BusinessLogicImplementationExtensions";
}
2024-05-16 17:00:28 +04:00
private static string TryGetImplementationExtensionsFolder()
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null && !directory.GetDirectories("ImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions"))
{
directory = directory.Parent;
}
return $"{directory?.FullName}\\ImplementationExtensions";
}
}
}