Skip to content

Commit

Permalink
Added isolated assembly loading for issue MapsterMapper#714
Browse files Browse the repository at this point in the history
  • Loading branch information
boylec committed Jun 14, 2024
1 parent 09a0e92 commit 6bf64b4
Show file tree
Hide file tree
Showing 3 changed files with 299 additions and 101 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,8 @@ project.lock.json
/src/.vs
/.vs
src/.idea

# VS Code settings
.vscode/launch.json
.vscode/settings.json
.vscode/tasks.json
76 changes: 76 additions & 0 deletions src/Mapster.Tool/IsolatedAssemblyLoadContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using CommandLine;
using ExpressionDebugger;
using Mapster.Models;
using Mapster.Utils;
using System;
using System.Reflection;
using System.Runtime.Loader;

namespace Mapster.Tool
{
public class IsolatedAssemblyContext : AssemblyLoadContext
{
private readonly AssemblyDependencyResolver resolver;

public IsolatedAssemblyContext(string assemblyPath)
{
resolver = new AssemblyDependencyResolver(assemblyPath);
}

protected override Assembly Load(AssemblyName assemblyName)
{
string assemblyPath = resolver.ResolveAssemblyToPath(assemblyName);
if (assemblyPath != null)
{
return LoadFromAssemblyPath(assemblyPath);
}

return null;
}

protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string libraryPath = resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
if (libraryPath != null)
{
return LoadUnmanagedDllFromPath(libraryPath);
}

return IntPtr.Zero;
}

public static Assembly LoadAssemblyFrom(string relativePath)
{
// Navigate up to the solution root
string root = Path.GetFullPath(
Path.Combine(
Path.GetDirectoryName(
Path.GetDirectoryName(
Path.GetDirectoryName(
Path.GetDirectoryName(
Path.GetDirectoryName(typeof(Program).Assembly.Location)
)
)
)
)
)
);

string assemblyLocation = Path.GetFullPath(
Path.Combine(root, relativePath.Replace('\\', Path.DirectorySeparatorChar))
);
Console.WriteLine($"Loading commands from: {assemblyLocation}");
IsolatedAssemblyContext loadContext = new IsolatedAssemblyContext(assemblyLocation);
return loadContext.LoadFromAssemblyName(
new AssemblyName(Path.GetFileNameWithoutExtension(assemblyLocation))
);
}
}
}
Loading

0 comments on commit 6bf64b4

Please sign in to comment.