This repository was archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathAppDomainContext.cs
76 lines (66 loc) · 2.46 KB
/
AppDomainContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Reflection;
using System.Collections.Generic;
namespace GitHub.UI.Helpers.UnitTests
{
public class AppDomainContext : IDisposable
{
AppDomain domain;
public static void Invoke(AppDomainSetup setup, Action remoteAction)
{
using (var context = new AppDomainContext(setup))
{
context.Invoke(remoteAction);
}
}
public AppDomainContext(AppDomainSetup setup = null)
{
if (setup == null)
{
setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; // don't use the process base dir
}
var friendlyName = GetType().FullName;
domain = AppDomain.CreateDomain(friendlyName, null, setup);
}
public void Dispose()
{
AppDomain.Unload(domain);
}
public void Invoke(Action remoteAction)
{
var targetType = remoteAction.Target.GetType();
var fieldValues = new Dictionary<string, object>();
foreach (var field in targetType.GetFields())
{
var value = field.GetValue(remoteAction.Target);
fieldValues[field.Name] = value;
}
var remove = CreateInstance<Remote>();
var assemblyFile = targetType.Assembly.Location;
var typeName = targetType.FullName;
var methodName = remoteAction.Method.Name;
remove.Invoke(assemblyFile, typeName, methodName, fieldValues);
}
public T CreateInstance<T>()
{
return (T)domain.CreateInstanceFromAndUnwrap(typeof(T).Assembly.CodeBase, typeof(T).FullName);
}
class Remote : MarshalByRefObject
{
internal void Invoke(string assemblyFile, string typeName, string methodName, Dictionary<string, object> fieldValues)
{
var assembly = Assembly.LoadFrom(assemblyFile);
var type = assembly.GetType(typeName);
var obj = Activator.CreateInstance(type);
foreach (var field in type.GetFields())
{
var value = fieldValues[field.Name];
field.SetValue(obj, value);
}
var dele = (Action)Delegate.CreateDelegate(typeof(Action), obj, methodName);
dele();
}
}
}
}