hybridclr_unity/Editor/Meta/AssemblyCache.cs

98 lines
2.8 KiB
C#
Raw Normal View History

2022-09-22 08:56:07 +08:00
using dnlib.DotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace HybridCLR.Editor.Meta
{
public class AssemblyCache : IDisposable
2022-09-22 08:56:07 +08:00
{
private readonly IAssemblyResolver _assemblyPathResolver;
private readonly ModuleContext _modCtx;
private readonly AssemblyResolver _asmResolver;
private bool disposedValue;
2023-11-01 20:33:42 +08:00
private bool _loadedNetstandard;
2022-09-22 08:56:07 +08:00
public Dictionary<string, ModuleDefMD> LoadedModules { get; } = new Dictionary<string, ModuleDefMD>();
public AssemblyCache(IAssemblyResolver assemblyResolver)
{
_assemblyPathResolver = assemblyResolver;
_modCtx = ModuleDef.CreateModuleContext();
_asmResolver = (AssemblyResolver)_modCtx.AssemblyResolver;
_asmResolver.EnableTypeDefCache = true;
_asmResolver.UseGAC = false;
}
public ModuleDefMD LoadModule(string moduleName, bool loadReferenceAssemblies = true)
2022-09-22 08:56:07 +08:00
{
// Debug.Log($"load module:{moduleName}");
if (LoadedModules.TryGetValue(moduleName, out var mod))
{
return mod;
}
2023-11-01 20:33:42 +08:00
if (moduleName == "netstandard")
{
if (!_loadedNetstandard)
{
LoadNetStandard();
_loadedNetstandard = true;
}
return null;
}
2022-09-22 08:56:07 +08:00
mod = DoLoadModule(_assemblyPathResolver.ResolveAssembly(moduleName, true));
LoadedModules.Add(moduleName, mod);
if (loadReferenceAssemblies)
2022-09-22 08:56:07 +08:00
{
foreach (var refAsm in mod.GetAssemblyRefs())
{
LoadModule(refAsm.Name);
}
2022-09-22 08:56:07 +08:00
}
2022-09-22 08:56:07 +08:00
return mod;
}
2023-11-01 20:33:42 +08:00
private void LoadNetStandard()
{
LoadModule("netstandard2.0", false);
LoadModule("netstandard2.1", false);
}
2022-09-22 08:56:07 +08:00
private ModuleDefMD DoLoadModule(string dllPath)
{
//Debug.Log($"do load module:{dllPath}");
ModuleDefMD mod = ModuleDefMD.Load(dllPath, _modCtx);
_asmResolver.AddToCache(mod);
return mod;
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
foreach(var mod in LoadedModules.Values)
{
mod.Dispose();
}
LoadedModules.Clear();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
2022-09-22 08:56:07 +08:00
}
}