Files
PIbd-32_BuslaevRoman_KOP/WinFormsComponentOrientedHost/Composition/ReflectionLoader.cs
2025-09-23 14:07:38 +04:00

61 lines
1.8 KiB
C#

using ComponentOrientedPlatform.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsComponentOrientedHost.Composition;
public sealed class ReflectionLoader
{
private readonly string _pluginsPath;
private readonly IAppLogger _log;
public ReflectionLoader(string pluginsPath, IAppLogger log)
{
_pluginsPath = Path.GetFullPath(pluginsPath);
_log = log;
Directory.CreateDirectory(_pluginsPath);
}
public IReadOnlyList<IComponentContract> LoadAll()
{
var result = new List<IComponentContract>();
foreach (var dll in Directory.EnumerateFiles(_pluginsPath, "*.dll"))
{
try
{
_log.Info($"Scanning: {dll}");
var asm = Assembly.LoadFrom(dll);
var types = asm.GetTypes()
.Where(t => !t.IsAbstract && typeof(IComponentContract).IsAssignableFrom(t));
foreach (var t in types)
{
try
{
if (Activator.CreateInstance(t) is IComponentContract instance)
{
result.Add(instance);
_log.Info($"Loaded component: {instance.Metadata.Title} ({instance.Metadata.Id})");
}
}
catch (Exception ex)
{
_log.Error($"Failed to instantiate {t.FullName}", ex);
}
}
}
catch (Exception ex)
{
_log.Error($"Failed to load assembly: {dll}", ex);
}
}
return result;
}
}