Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 515
xwrs Avatar asked Sep 14 '12 10:09

xwrs


3 Answers

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();
like image 96
Andrii Kalytiiuk Avatar answered Oct 21 '22 15:10

Andrii Kalytiiuk


It is possible that the type is in an assembly that has not yet been loaded. Later in your program it then is. If you look at the output window this should give you sn idea of when the assemblies are being loaded.

like image 21
Justin Harvey Avatar answered Oct 21 '22 16:10

Justin Harvey


Another answer shows the best way for obtaining (at runtime) a Type defined in an Assembly that might not be loaded:

var T1 = Type.GetType("System.Web.Configuration.IAssemblyCache, " + 
                      "System.Web, " + 
                      "Version=4.0.0.0, " + 
                      "Culture=neutral, " + 
                      "PublicKeyToken=b03f5f7f11d50a3a");

As you can see, unfortunately that method requires you to supply the full AssemblyQualifiedName of the Type and will not work with any of the abbreviated forms of the assembly name that I tried. This somewhat defeats our main purposes here. If you knew that much detail about the assembly, it wouldn't be that much harder to just load it yourself:

var T2 = Assembly.Load("System.Web, " + 
                       "Version=4.0.0.0, " + 
                       "Culture=neutral, " + 
                       "PublicKeyToken=b03f5f7f11d50a3a")
                 .GetType("System.Web.Configuration.IAssemblyCache");

Although these two examples look similar, they execute very different code paths; note for example, that the latter version calls an instance overload on Assembly.GetType versus the static call Type.GetType. Because of this, the second version is probably faster or more efficient. Either way, though, you seem to end up at the following CLR internal method, and with the second argument set to false, and this is why neither method goes to the trouble of searching for the required assembly on your behalf.

[System.Runtime.Remoting.RemotingServices]
private static RuntimeType LoadClrTypeWithPartialBindFallback(
                  String typeName,
                  bool partialFallback);

A tiny step forward from these inconveniences would be to instead call this CLR method yourself, but with the partialFallback parameter set to true. In this mode, the function will accept a truncated version of the AssemblyQualifiedName and will locate and load the relevant assembly, as necessary:

static Func<String, bool, TypeInfo> LoadClrTypeWithPartialBindFallback =
    typeof(RemotingServices)
    .GetMethod("LoadClrTypeWithPartialBindFallback", (BindingFlags)0x28)
    .CreateDelegate(typeof(Func<String, bool, TypeInfo>))
    as Func<String, bool, TypeInfo>;

// ...

var T3 = LoadClrTypeWithPartialBindFallback(
            "System.Web.Configuration.IAssemblyCache, System.Web",
            true);    //  <-- enables searching for the assembly

This works as shown, and also continues to support specifying the full AssemblyQualifiedName as in the earlier examples. This is a small improvement, but it's still not a fully unqualified namespace search, because you do still have to specify the short name of the assembly, even if it might be deduced from the namespace that appears in the type name itself.

like image 1
Glenn Slayden Avatar answered Oct 21 '22 15:10

Glenn Slayden