summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/ModLoading/AssemblyDefinitionResolver.cs
blob: 9867ed8b039beec5c54b00b5bca876aa827e63fa (plain)
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
extern alias MonoCecilPackage;

using System.Collections.Generic;
using MonoCecilPackage.Mono.Cecil;

namespace StardewModdingAPI.Framework.ModLoading
{
    /// <summary>A minimal assembly definition resolver which resolves references to known assemblies.</summary>
    internal class AssemblyDefinitionResolver : DefaultAssemblyResolver
    {
        /*********
        ** Fields
        *********/
        /// <summary>The known assemblies.</summary>
        private readonly IDictionary<string, AssemblyDefinition> Lookup = new Dictionary<string, AssemblyDefinition>();


        /*********
        ** Public methods
        *********/
        /// <summary>Add known assemblies to the resolver.</summary>
        /// <param name="assemblies">The known assemblies.</param>
        public void Add(params AssemblyDefinition[] assemblies)
        {
            foreach (AssemblyDefinition assembly in assemblies)
            {
                this.RegisterAssembly(assembly);
                this.Lookup[assembly.Name.Name] = assembly;
                this.Lookup[assembly.Name.FullName] = assembly;
            }
        }

        /// <summary>Resolve an assembly reference.</summary>
        /// <param name="name">The assembly name.</param>
        public override AssemblyDefinition Resolve(AssemblyNameReference name) => this.ResolveName(name.Name) ?? base.Resolve(name);

        /// <summary>Resolve an assembly reference.</summary>
        /// <param name="name">The assembly name.</param>
        /// <param name="parameters">The assembly reader parameters.</param>
        public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) => this.ResolveName(name.Name) ?? base.Resolve(name, parameters);


        /*********
        ** Private methods
        *********/
        /// <summary>Resolve a known assembly definition based on its short or full name.</summary>
        /// <param name="name">The assembly's short or full name.</param>
        private AssemblyDefinition ResolveName(string name)
        {
            return this.Lookup.TryGetValue(name, out AssemblyDefinition match)
                ? match
                : null;
        }
    }
}