Skip to content

Commit

Permalink
Simplify loading assemblies
Browse files Browse the repository at this point in the history
Use a HashSet instead of a Dictionary keyed by the assembly full name. If an assembly is loaded twice with the same AssemblyName it will be the same instance so a HashSet (without even a custom IEqualityComparer<Assembly>) is the perfect solution.

Also, Assembly.Load can throw many exceptions but won't return null.
  • Loading branch information
0xced committed Mar 27, 2023
1 parent 92d37fc commit 74402f8
Showing 1 changed file with 4 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ internal static IConfigurationArgumentValue GetArgumentValue(IConfigurationSecti
static IReadOnlyCollection<Assembly> LoadConfigurationAssemblies(IConfiguration section, AssemblyFinder assemblyFinder)
{
var serilogAssembly = typeof(ILogger).Assembly;
var assemblies = new Dictionary<string, Assembly> { [serilogAssembly.FullName] = serilogAssembly };
var assemblies = new HashSet<Assembly> { serilogAssembly };

var usingSection = section.GetSection("Using");
if (usingSection.GetChildren().Any())
Expand All @@ -371,16 +371,14 @@ static IReadOnlyCollection<Assembly> LoadConfigurationAssemblies(IConfiguration
$"A zero-length or whitespace assembly name was supplied to a {usingSection.Path} configuration statement.");

var assembly = Assembly.Load(new AssemblyName(simpleName));
if (!assemblies.ContainsKey(assembly.FullName))
assemblies.Add(assembly.FullName, assembly);
assemblies.Add(assembly);
}
}

foreach (var assemblyName in assemblyFinder.FindAssembliesContainingName("serilog"))
{
var assumed = Assembly.Load(assemblyName);
if (assumed != null && !assemblies.ContainsKey(assumed.FullName))
assemblies.Add(assumed.FullName, assumed);
assemblies.Add(assumed);
}

if (assemblies.Count == 1)
Expand All @@ -395,7 +393,7 @@ This is most likely because the application is published as single-file.
throw new InvalidOperationException(message);
}

return assemblies.Values;
return assemblies;
}

void CallConfigurationMethods(ILookup<string, Dictionary<string, IConfigurationArgumentValue>> methods, IReadOnlyCollection<MethodInfo> configurationMethods, object receiver)
Expand Down

0 comments on commit 74402f8

Please sign in to comment.