添加插件域检测

This commit is contained in:
2248356998 qq.com
2023-03-13 09:24:07 +08:00
parent f42cbc1789
commit e111565d8a
2 changed files with 39 additions and 2 deletions

View File

@@ -10,6 +10,8 @@ using System.Runtime.Loader;
using ThingsGateway.Core.Extension;
using TouchSocket.Core;
namespace ThingsGateway.Web.Foundation;
/// <summary>
/// 驱动插件服务
@@ -29,6 +31,10 @@ public class PluginCore : ISingleton
/// </summary>
public ConcurrentDictionary<long, AssemblyLoadContext> AssemblyLoadContexts { get; private set; } = new();
/// <summary>
/// 旧插件域
/// </summary>
public ConcurrentList<WeakReference> WeakReferences { get; private set; } = new();
/// <summary>
/// 插件ID/插件Type
/// </summary>
public ConcurrentDictionary<long, Type> DriverPlugins { get; private set; } = new();
@@ -216,17 +222,42 @@ public class PluginCore : ISingleton
public void DeleteDriver(long devId, long pluginId)
{
try
{
foreach (WeakReference item in WeakReferences)
{
if (item.IsAlive)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
else
{
WeakReferences.Remove(item);
}
}
}
catch
{
}
if (DeviceOnDriverPlugins.ContainsKey(pluginId))
{
DeviceOnDriverPlugins[pluginId].Remove(devId);
if (DeviceOnDriverPlugins[pluginId].Count == 0)
{
DeviceOnDriverPlugins.Remove(pluginId);
DriverPlugins.Remove(pluginId);
var assemblyLoadContext = AssemblyLoadContexts.GetValueOrDefault(pluginId);
if (assemblyLoadContext != null)
{
assemblyLoadContext.Unload();
AssemblyLoadContexts.Remove(pluginId);
WeakReference alcWeakRef = new WeakReference(assemblyLoadContext, true);
WeakReferences.Add(alcWeakRef);
assemblyLoadContext.Unload();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}

View File

@@ -1,4 +1,5 @@
@using System.Reflection;
@using ThingsGateway.Web.Foundation;
@inject NavigationManager NavigationManager
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(BlazorApp).Assembly" AdditionalAssemblies=@(GetAssemblys())>
@@ -29,12 +30,17 @@
</Router>
</CascadingAuthenticationState>
@code {
[Inject]
IDriverPluginService DriverPluginService { get; set; }
IEnumerable<Assembly> GetAssemblys()
{
var plugins = DriverPluginService.GetCacheListAsync();
var controllerTypes = App.EffectiveTypes.
Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
&& u.IsDefined(typeof(Microsoft.AspNetCore.Components.RouteAttribute), false))
.Where(it => it.Assembly != typeof(BlazorApp).Assembly);
.Where(it => it.Assembly != typeof(BlazorApp).Assembly)
.Where(a => !(plugins.Select(b=>b.AssembleName).Contains(a.ToString())))
;
var assemblys = controllerTypes?.Select(it => it.Assembly)?.Distinct();
return assemblys;
}