Search code examples
c#.netreflectionappdomain

Searching type in assemblies


I had an issue that code Type.GetType(myTypeName) was returning null because assembly with that type is not current executing assembly.

The solution I found for this issue is next:

var assemblies = AppDomain.CurrentDomain.GetAssemblies();
Type myType = assemblies.SelectMany(a => a.GetTypes())
                        .Single(t => t.FullName == myTypeName);

The problem is that the first run of this code causes exception "Sequence contains no matching element". When I call this part of code again - everything is ok and needed Type is loaded.

Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?


Solution

  • Problem you are facing is caused by design of GetAssemblies method of AppDomain class - according to documentation this method:

    Gets the assemblies that have been loaded into the execution context of this application domain.

    So when in your program type fails to be found first time - its assembly isn't obviously loaded by the application yet. And afterwards - when some functionality from assembly that contains type in question had been used - assembly is already loaded, and same code can already find missing type.

    Please try loading assemblies directly. Instead of using:

    var assemblies = AppDomain.CurrentDomain.GetAssemblies();
    

    you can use:

    List<Assembly> assemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies().Select(assembly => Assembly.LoadFrom(assembly.Name)).ToList();