DepartmentProject/DepartmentPortal/Common/ModelTools/BusinessLogics/ServiceProviderLoader.cs

79 lines
2.2 KiB
C#
Raw Normal View History

using ModelTools.Extensions;
using ModelTools.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.XPath;
namespace ModelTools.BusinessLogics
{
/// <summary>
/// Загрузчик данных
/// </summary>
public static class ServiceProviderLoader
{
private static readonly string _configFileName = "DepartmentPortal.config";
private static readonly string _pathToLoaderExt = "..\\..\\..\\..\\Extensions\\";
/// <summary>
/// Получение данных с файла настроек
/// </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>
/// Загрузка всех классов-реализаций ILoaderExtensions
/// </summary>
/// <returns></returns>
public static List<ILoaderExtensions> GetLoaderExtensions()
{
var list = new List<ILoaderExtensions>();
if(Directory.Exists(_pathToLoaderExt))
{
var files = Directory.GetFiles(_pathToLoaderExt, "*.dll", SearchOption.AllDirectories);
var loadedFiles = new List<string>();
foreach(var file in files.Distinct())
{
if(loadedFiles.Contains(file.GetFileName()))
{
continue;
}
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(ILoaderExtensions).IsAssignableFrom(t))
{
list.Add((ILoaderExtensions)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);
}
}