.NET, Reflection and multiple assemblies

As part of a project I worked on at Mindseye, I wrote a couple utilities using C# that used reflection to query a given type for the existence of a method and if the method existed, to then invoke the method. In short, the utility allowed me to do this (pseudo-code):

AbstractType type = AbstractTypeFactory.Find("com.company.SomeClass");
string result = type.InvokeMethod("delete");

The AbstractTypeFactory type has a single static method ‘Find()’ that looks for the given type by name. If successful, it returns an instance of AbstractType, which you can use to invoke a given method on the type you looked up using the InvokeMethod() method. The InvokeMethod() method checks to see if the given method is a static or instance method, creates an instance if necessary, and then calls the method.

These utilities worked fine until I need to call the Find() method against a type that wasn’t in the same assembly as the assembly that my utility was in. Inside the AbStractTypeFactory (which is a pseudo-name by the way), I used the .NET Type class:

// Gets the Type with the specified name, performing a case-sensitive search.
Type type = Type.GetType("com.company.SomeClass");

I didn’t have time to look into why the GetType() method wouldn’t find types outside of the currently assembly… until today when I really needed to be use the utilities against a different assembly. It turns out that it’s relatively simple to do. Instead of using the type name (ie: “com.company.SomeClass”), you can use the AssemblyQualifiedName, which looks likes this:

com.company.SomeClass, assemblyname, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

where assemblyname is the name of the DLL that com.company.SomeClass exists in. It’s relatively easy to retrieve the AssemblyQualifiedName using the AssemblyQualifiedName property of the Type type. For example, the .NET documentation gives this example:

Type objType = typeof(System.Array);
Console.WriteLine ("Qualified assembly name: {0}.", objType.AssemblyQualifiedName.ToString());

There are alot of good reasons why Microsoft designed the GetType() method the way they did, the majority of them related to how the runtime locates assemblies, which you should read about when you have a alot of time.

One thought on “.NET, Reflection and multiple assemblies”

  1. Thanks! You just stopped me from banging my head repeatedly against a wall trying to write a generic Enum edit control for ASP.NET! :o)

Leave a Reply

Your email address will not be published. Required fields are marked *