Shachaf.Gortler Shachaf.Gortler -4 years ago 164
C# Question

ReflectionTypeLoadException Unable to load one or > more of the requested types

I have the following code , that loades all aseemblies that are refrenced by my porject and all referenced used by them

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())
.Where(t => t.IsClass && !t.IsAbstract && (typeof (MyType).IsAssignableFrom(t)));


foreach (var type in types.Where(type => typeof (MyType).IsAssignableFrom(type)))
{... do something ...}


On my dev box this works as expected , on other environment this causes an exception


System.Reflection.ReflectionTypeLoadException: Unable to load one or
more of the requested types. Retrieve the LoaderExceptions property
for more information.


Why is that exception thrown ?
is it possible to refactor my code to make it so that exception is ignored ?

Answer Source

I had the exact same issue but the Assembly it was having issues with I didn't really care about.

I went from this (worked locally):

Type t = AppDomain.CurrentDomain.GetAssemblies()
              .SelectMany(a => a.GetTypes())
              .Where(a => a.FullName == clientEx.ExceptionType)
              .FirstOrDefault();

To this:

Type t = null;

foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
    try
    {
        foreach (Type type in a.GetTypes())
        {
            if (type.FullName == clientEx.ExceptionType)
            {
                t = type;
                break;
            }                                            
        }

        if (t != null)
            break;
    }
    catch (Exception) { }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download