86 lines
3.1 KiB
C#
Executable File
86 lines
3.1 KiB
C#
Executable File
using System;
|
|
using System.Linq.Expressions;
|
|
using System.Reflection;
|
|
using System.Threading;
|
|
|
|
namespace Opsoft.NetCore.O3App.Shared.Data
|
|
{
|
|
internal class ExtensionLoader
|
|
{
|
|
private static ExtensionLoader _instance;
|
|
|
|
private static object _syncRoot = new object();
|
|
|
|
private BlockingDictionary<string, Assembly> _assemblyCache;
|
|
|
|
private BlockingDictionary<Assembly, BlockingDictionary<Type, object>> _extensionCache;
|
|
|
|
public static ExtensionLoader Instance
|
|
{
|
|
get
|
|
{
|
|
ExtensionLoader instance = _instance;
|
|
if (instance == null)
|
|
{
|
|
lock (_syncRoot)
|
|
{
|
|
instance = Volatile.Read(ref _instance);
|
|
if (instance == null)
|
|
{
|
|
instance = new ExtensionLoader();
|
|
}
|
|
Volatile.Write(ref _instance, instance);
|
|
return instance;
|
|
}
|
|
}
|
|
return instance;
|
|
}
|
|
}
|
|
|
|
private ExtensionLoader()
|
|
{
|
|
_assemblyCache = new BlockingDictionary<string, Assembly>();
|
|
_extensionCache = new BlockingDictionary<Assembly, BlockingDictionary<Type, object>>();
|
|
}
|
|
|
|
internal T GetService<T>(string assemblyName)
|
|
{
|
|
Assembly extensionAssembly = _assemblyCache.GetOrAdd(assemblyName, delegate
|
|
{
|
|
AssemblyName assemblyRef = new AssemblyName(assemblyName);
|
|
Assembly assembly = null;
|
|
try
|
|
{
|
|
assembly = Assembly.Load(assemblyRef);
|
|
}
|
|
catch
|
|
{
|
|
//Log.Warn(ex, ex.Message);
|
|
}
|
|
if (assembly == null)
|
|
{
|
|
string message2 = assemblyName + ".dll未找到,请安装" + assemblyName + "组件NuGet包";
|
|
//Log.Error(message2);
|
|
throw new TypeLoadException(message2);
|
|
}
|
|
return assembly;
|
|
});
|
|
BlockingDictionary<Type, object> orAdd = _extensionCache.GetOrAdd(extensionAssembly, (Assembly _) => new BlockingDictionary<Type, object>());
|
|
Type baseType = typeof(T);
|
|
return (T)orAdd.GetOrAdd(baseType, delegate
|
|
{
|
|
foreach (Type exportedType in extensionAssembly.ExportedTypes)
|
|
{
|
|
if (baseType.IsAssignableFrom(exportedType))
|
|
{
|
|
return Expression.Lambda<Func<T>>(Expression.Property(null, exportedType, "Instance"), Array.Empty<ParameterExpression>()).Compile()();
|
|
}
|
|
}
|
|
string message = "在" + assemblyName + "中未找到" + baseType.FullName + "的实现类";
|
|
//Log.Error(message);
|
|
throw new TypeLoadException(message);
|
|
});
|
|
}
|
|
}
|
|
}
|