DepartmentProject/DepartmentPortal/Common/ToolsModule/ManagmentDependency/ServiceProviderLoader.cs

83 lines
2.5 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.XPath;
2022-03-20 10:10:44 +04:00
using ToolsModule.ManagmentExtension;
2022-03-20 10:10:44 +04:00
namespace ToolsModule.ManagmentDependency
{
/// <summary>
/// Загрузчик данных
/// </summary>
public static partial class ServiceProviderLoader
{
private static readonly string _configFileName = "DepartmentPortal.config";
/// <summary>
/// Получение данных с файла настроек (для releaze версии сборки)
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetConfigData(string key)
{
var fileName = GetFile(_configFileName);
if (!File.Exists(fileName))
{
return string.Empty;
}
var doc = new XPathDocument(fileName);
var nav = doc.CreateNavigator();
var data = nav.SelectDescendants(key, "", false);
data.MoveNext();
return data.Current.Value;
}
/// <summary>
/// Загрузка всех классов-реализаций IImplementationExtension
/// </summary>
/// <returns></returns>
public static List<IDependencyRegistration> GetImplementationExtensions()
{
var list = new List<IDependencyRegistration>();
var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
var loadedFiles = new List<string>();
foreach (var file in files.Distinct())
{
if (loadedFiles.Contains(file.GetFileName()))
{
continue;
}
var asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IDependencyRegistration).IsAssignableFrom(t))
{
list.Add((IDependencyRegistration)Activator.CreateInstance(t));
}
}
loadedFiles.Add(file.GetFileName());
}
return list;
}
/// <summary>
/// Получение имени файла
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private static string GetFile(string fileName) => Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), fileName);
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";
}
}
}