views:

65

answers:

3

I am needing to reference a type in an external assembly. I know the namespace and the type name and I know the assembly will be in the GAC, but that's it. Is there a way to get this type. I see there's a way to get it from a GUID or Program ID which works for me, but I know the people who develop the external assembly may drift away from these COM-like attributes. So, I don't want to depend on them.

Just for a frame of reference, I'd like my software to be very versatile when it comes to this external software being upgraded. So I can't depend on certain versions of assemblies being there for me.

A: 

You can load an assembly by name if its in the GAC and then iterate though all its types using Assembly.GetTypes(). You can use loadpartialname but its deprecated to get an assembly with out the fully qualified name.

Look at Assembly.Load()
and Assembly.GetType()

rerun
A: 

Since you know this is guaranteed to be in the GAC, you could list the results of gacutil /l. This will give you a list of every assembly in the GAC.

From that, you could start a loop that did the following:

foreach assemblyName in list
    Create new AppDomain
    Load assembly into new appdomain
    check for type in assembly
    if exists:
        return assemblyName to main appDomain
    Unload appdomain

It's important to do this in a separate AppDomain, or you'll load all of these assemblies permanently into your program.

Note that this is going to be very, very slow, and not exactly something I'd recommend. Once you know the proper type name, you should most likely cache this in your app settings for future loads.


Edit:

As Hans points out, Gacutil requires a .NET SDK installation to use. If this is not a valid option, you can use C++/CLI to make a .NET accessable API to retrieve information from the GAC. There is a Native API for accessing GAC information, but this is not a managed API.

Reed Copsey
Gacutil isn't available on a .NET install, SDK required.
Hans Passant
@Hans: True - it requires a full SDK install.
Reed Copsey
@Hans: I added how to do this from C++ - it could be wrapped via C++/CLI and used instead of Gacutil, as well...
Reed Copsey
I did post about it a while ago, showing how to use the interface in C#: http://stackoverflow.com/questions/2611108/register-a-dll-into-the-gac-but-then-it-doesnt-show-up-in-the-assembly-window/2611435#2611435
Hans Passant
A: 

Do you know the assemblyname or do you not know?
if you know the assembylname than it is easy:

Object Creator(string assemblyname, string classname) 
{
   System.Type objType = System.Type.GetType(assemblyname + "." + classname);
   Return Activator.CreateInstance(objType);
}
Oops