voile/Voile.Patchouli/Reflection/VoilePluginManager.cs

112 lines
3.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Voile.Common.Logging;
using Voile.Common.Reflection;
using Voile.Patchouli.Data;
namespace Voile.Patchouli.Reflection
{
public class VoilePluginManager
{
private VoilePluginManager() { }
public static VoilePluginManager _instance;
private static Type _dataStorageFactoryType = typeof(IVoileDataStorageFactory);
private static Type _objectStorageFactoryType = typeof(IVoileObjectStorageFactory);
private static VoileLogger logger;
public static VoilePluginManager GetInstance()
{
if (_instance == null)
{
_instance = new VoilePluginManager();
logger = VoileLogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
}
return _instance;
}
private List<Assembly> _loadedAssemblies;
private List<VoilePluginInfo> _knownDataStorages;
private List<VoilePluginInfo> _knownObjectStorages;
public bool ScanAssembly(Assembly assembly)
{
if (_loadedAssemblies == null)
_loadedAssemblies = new List<Assembly>();
if (_loadedAssemblies.Contains(assembly))
return false;
logger.Info("Scanning assembly: {0}", assembly.GetName().Name);
bool result = false;
Type[] types = assembly.GetTypes();
foreach (Type t in types)
{
if (ScanType(t))
result = true;
}
return result;
}
public bool ScanType(Type t)
{
VoilePluginAttribute? voilePluginAttribute = t.GetCustomAttribute<VoilePluginAttribute>();
if (voilePluginAttribute == null)
return false;
VoilePluginIdAttribute? voilePluginIdAttribute = t.GetCustomAttribute<VoilePluginIdAttribute>();
if (voilePluginIdAttribute == null)
return false;
VoilePluginInfo child = new VoilePluginInfo(t);
child.Id = voilePluginIdAttribute.Id;
if (t.IsAssignableTo(_dataStorageFactoryType))
{
if (_knownDataStorages == null)
_knownDataStorages = new List<VoilePluginInfo>();
child.Subsystem = VoileSubsystemType.DataStorage;
_knownDataStorages.Add(child);
return true;
}
else if (t.IsAssignableTo(_objectStorageFactoryType))
{
if (_knownObjectStorages == null)
_knownObjectStorages = new List<VoilePluginInfo>();
child.Subsystem = VoileSubsystemType.ObjectStorage;
_knownObjectStorages.Add(child);
return true;
}
else
{
throw new VoileReflectionException(String.Format("Could not figure out plugin type of {0}", t.Name));
}
}
public IReadOnlyList<VoilePluginInfo> GetDataStorages()
{
if (_knownDataStorages == null)
{
return new List<VoilePluginInfo>();
}
return _knownDataStorages.AsReadOnly();
}
public DirectoryInfo GetVoileHomeDirectory()
{
Assembly? assembly = Assembly.GetEntryAssembly();
string location = assembly.Location;
FileInfo locationFi = new FileInfo(location);
DirectoryInfo directory = locationFi.Directory;
return directory;
}
}
}