Update TypeSourceSelector.cs by peterhel · Pull Request #230 · khellang/Scrutor (original) (raw)
I've converted the full version of my original with logging (updated to use MEL instead of L4N) to c# below. I don't know if it adds much, but it might be useful for some users with debugging.
using Microsoft.Extensions.Logging;
namespace System.Reflection;
public static class AssemblyTypeExtensions { public static Type[] GetLoadableTypes(this Assembly assembly) => assembly.GetLoadableTypes(Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
public static Type[] GetLoadableTypes(this Assembly assembly, ILogger logger)
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
using var scope = logger.BeginScope("Loading types from {assemblyName}", assembly.FullName);
logger.LogWarning(ex, "Issue loading types from {assemblyName}", assembly.FullName);
foreach (var le in ex.LoaderExceptions.Where(e => e is not null).OfType<Exception>())
{
if (le is TypeLoadException tle)
{
logger.LogWarning(tle, "TypeLoadException for {typeName} in {assemblyName}", tle.TypeName, assembly.FullName);
}
else
{
logger.LogWarning(le, "{exceptionType}: {message}", le.GetType().Name, le.Message);
}
}
return ex.Types.Where(t => t is not null).ToArray()!;
}
catch (Exception ex)
{
logger.LogWarning(ex, "Failed to load types from {assemblyName}", assembly.FullName);
return [];
}
}}