I’ve got to allow users an easy way to identify a type in an assembly, then get the corresponding Type object.
I could, hypothetically, require they give me an assembly qualified name, but its a bit klunky, and can be hard to figure out if the assembly is signed. It would be easier on my part, however, as I could use Type.GetType(string) to get my type object.
If I allow my users to provide me a namespace-qualified type name (Namespace.Type), I cannot use Type.GetType to find my type object. Which leads me to my question.
As far as I know, the only way to do this is to spelunk through the current AppDomain (assuming the type’s assembly is loaded–which in my case will be true), and search through all the assemblies and their types for matching names (Type.FullName). Since the app domain has over 80 assemblies loaded with thousands of types defined, this can cause some delay in the UI (I’m doing this within an IValueConverter).
To mitigate this, I use a list of well known assembly public key tokens to weed out all the assemblies I know that will be loaded and will not contain the types I’m looking for. This solution is moderately successful.
My question is, are there faster, better ways that I can use to find a Type in the current AppDomain that matches a string containing its FullName?
Here’s my current code:
private static string[] wellKnownTokens = new string[] {
"b03f5f7f11d50a3a",
"4fe470e63e2d354f",
"b77a5c561934e089",
"31bf3856ad364e35" };
private Type GetTypeFromFullName(string fullName)
{
var assys = from x in AppDomain.CurrentDomain.GetAssemblies()
where !wellKnownTokens.Any(y => x.FullName.EndsWith(y))
select x;
return (from x in assys.SelectMany(x => x.GetTypes())
where x.FullName == typeName
select x).FirstOrDefault();
}
One approach would be to go through each assembly that is loaded (your 80 assemblies), and for each one append the assembly name to the type name (i.e. make the type name assembly qualififed) and then use
Type.GetType(string, boolean)[make sure the boolean throwOnErroris false]
Without looking at the implementation of
Type.GetType(string, boolean), I don’t know whether this would end up being faster than looping through all types in all assemblies or not.