From face8c73ee42b5dc401feca95b1efda9fe0cdf97 Mon Sep 17 00:00:00 2001 From: Kristian Hellang Date: Thu, 26 Sep 2024 07:39:32 +0200 Subject: [PATCH] Work around type load errors in .NET Framework --- src/Scrutor/ReflectionExtensions.cs | 17 +++++++++++++++++ src/Scrutor/TypeSourceSelector.cs | 4 ++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/Scrutor/ReflectionExtensions.cs b/src/Scrutor/ReflectionExtensions.cs index e8e41edf..e7dcde4d 100644 --- a/src/Scrutor/ReflectionExtensions.cs +++ b/src/Scrutor/ReflectionExtensions.cs @@ -218,6 +218,23 @@ private static bool GenericParametersMatch(IReadOnlyList parameters, IRead return true; } + // Workaround for type load issues in .NET Framework + public static IReadOnlyCollection GetLoadableTypes(this Assembly assembly) + { + try + { + return assembly.GetTypes(); + } + catch (ReflectionTypeLoadException ex) + { + return ex.Types.Where(t => t is not null).ToArray()!; + } + catch + { + return []; + } + } + public static string ToFriendlyName(this Type type) { return TypeNameHelper.GetTypeDisplayName(type, includeGenericParameterNames: true); diff --git a/src/Scrutor/TypeSourceSelector.cs b/src/Scrutor/TypeSourceSelector.cs index a393afbc..df5b9b07 100644 --- a/src/Scrutor/TypeSourceSelector.cs +++ b/src/Scrutor/TypeSourceSelector.cs @@ -42,7 +42,7 @@ public IImplementationTypeSelector FromCallingAssembly() { return FromAssemblies(Assembly.GetCallingAssembly()); } - + /// /// Always uses the Scrutor assembly. /// @@ -188,7 +188,7 @@ private IImplementationTypeSelector InternalFromAssembliesOf(IEnumerable t private IImplementationTypeSelector InternalFromAssemblies(IEnumerable assemblies) { - return AddSelector(assemblies.SelectMany(asm => asm.GetTypes())); + return AddSelector(assemblies.SelectMany(asm => asm.GetLoadableTypes())); } private static ISet LoadAssemblies(ISet assemblyNames)