2023-04-11 16:57:04 +04:00
|
|
|
|
using System.Reflection;
|
|
|
|
|
|
|
|
|
|
namespace IceCreamShopContracts.DI
|
|
|
|
|
{
|
|
|
|
|
public class ServiceProviderLoader
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Загрузка всех классов-реализаций IImplementationExtension
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <returns></returns>
|
2023-05-03 16:28:35 +04:00
|
|
|
|
public static List<IImplementationExtension?> GetImplementationExtensions()
|
2023-04-11 16:57:04 +04:00
|
|
|
|
{
|
2023-05-03 16:28:35 +04:00
|
|
|
|
Type[] handledTypes =
|
|
|
|
|
{
|
|
|
|
|
typeof(IImplementationBusinessLogicExtension),
|
|
|
|
|
typeof(IImplementationExtension)
|
|
|
|
|
};
|
|
|
|
|
var result = handledTypes.Select(x => (IImplementationExtension?)null).ToList();
|
2023-04-11 16:57:04 +04:00
|
|
|
|
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())
|
|
|
|
|
{
|
2023-05-03 16:28:35 +04:00
|
|
|
|
for (var i = 0; i < handledTypes.Length; i++)
|
2023-04-11 16:57:04 +04:00
|
|
|
|
{
|
2023-05-03 16:28:35 +04:00
|
|
|
|
if (t.IsClass && handledTypes[i].IsAssignableFrom(t))
|
2023-04-11 16:57:04 +04:00
|
|
|
|
{
|
2023-05-03 16:28:35 +04:00
|
|
|
|
if (result[i] == null)
|
|
|
|
|
{
|
|
|
|
|
result[i] = (IImplementationExtension)Activator.CreateInstance(t)!;
|
|
|
|
|
}
|
|
|
|
|
else
|
2023-04-11 16:57:04 +04:00
|
|
|
|
{
|
2023-05-03 16:28:35 +04:00
|
|
|
|
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
|
|
|
|
|
if (newSource.Priority > result[i].Priority)
|
|
|
|
|
{
|
|
|
|
|
result[i] = newSource;
|
|
|
|
|
}
|
2023-04-11 16:57:04 +04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-05-03 16:28:35 +04:00
|
|
|
|
return result;
|
2023-04-11 16:57:04 +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;
|
|
|
|
|
}
|
2023-04-12 12:04:35 +04:00
|
|
|
|
|
2023-04-11 16:57:04 +04:00
|
|
|
|
return $"{directory?.FullName}\\ImplementationExtensions";
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|