forked from seesharper/BasicFodyAddin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuleWeaver.cs
More file actions
72 lines (61 loc) · 2.22 KB
/
ModuleWeaver.cs
File metadata and controls
72 lines (61 loc) · 2.22 KB
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
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Rocks;
using Mono.Cecil.Cil;
using Fody;
#region ModuleWeaver
public class ModuleWeaver: BaseModuleWeaver
{
#region Execute
public override void Execute()
{
var ns = GetNamespace();
var newType = new TypeDefinition(ns, "Hello", TypeAttributes.Public, TypeSystem.ObjectReference);
AddConstructor(newType);
AddHelloWorld(newType);
ModuleDefinition.Types.Add(newType);
LogInfo("Added type 'Hello' with method 'World'.");
}
#endregion
#region GetAssembliesForScanning
public override IEnumerable<string> GetAssembliesForScanning()
{
yield return "netstandard";
yield return "mscorlib";
}
#endregion
string GetNamespace()
{
var attributes = ModuleDefinition.Assembly.CustomAttributes;
var namespaceAttribute = attributes.FirstOrDefault(x => x.AttributeType.FullName == "NamespaceAttribute");
if (namespaceAttribute == null)
{
return null;
}
attributes.Remove(namespaceAttribute);
return (string) namespaceAttribute.ConstructorArguments.First().Value;
}
void AddConstructor(TypeDefinition newType)
{
var method = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, TypeSystem.VoidReference);
var objectConstructor = ModuleDefinition.ImportReference(TypeSystem.ObjectDefinition.GetConstructors().First());
var processor = method.Body.GetILProcessor();
processor.Emit(OpCodes.Ldarg_0);
processor.Emit(OpCodes.Call, objectConstructor);
processor.Emit(OpCodes.Ret);
newType.Methods.Add(method);
}
void AddHelloWorld(TypeDefinition newType)
{
var method = new MethodDefinition("World", MethodAttributes.Public, TypeSystem.StringReference);
var processor = method.Body.GetILProcessor();
processor.Emit(OpCodes.Ldstr, "Hello World");
processor.Emit(OpCodes.Ret);
newType.Methods.Add(method);
}
#region ShouldCleanReference
public override bool ShouldCleanReference => true;
#endregion
}
#endregion