-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuleInit.cs
More file actions
41 lines (35 loc) · 1.11 KB
/
ModuleInit.cs
File metadata and controls
41 lines (35 loc) · 1.11 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
using System.Management.Automation;
using System.Reflection;
using PwshPrompt.Consts;
namespace PwshPrompt;
/// <summary>
/// Registers and removes custom type accelerators on module import/removal.
/// </summary>
public sealed class ModuleInit : IModuleAssemblyInitializer, IModuleAssemblyCleanup
{
private static readonly Dictionary<string, Type> _accelerators = new()
{
["Colors"] = typeof(Colors),
};
private static readonly MethodInfo? _addMethod;
private static readonly MethodInfo? _removeMethod;
static ModuleInit()
{
var type = typeof(PSObject).Assembly
.GetType("System.Management.Automation.TypeAccelerators");
_addMethod = type?.GetMethod("Add", BindingFlags.Public | BindingFlags.Static);
_removeMethod = type?.GetMethod("Remove", BindingFlags.Public | BindingFlags.Static);
}
/// <inheritdoc />
public void OnImport()
{
foreach (var (name, type) in _accelerators)
_addMethod?.Invoke(null, new object[] { name, type });
}
/// <inheritdoc />
public void OnRemove(PSModuleInfo module)
{
foreach (var name in _accelerators.Keys)
_removeMethod?.Invoke(null, new object[] { name });
}
}