Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Namespace, classname from a dll in C# 2.0

I will get dll's dynamically. I need to load the dll and get the namespace, classname to invoke a method (the method name is static it will be always "OnStart()"). Basically I need to run a method by loading the dll. Can somebody help!!!.

like image 490
balaji Avatar asked Oct 20 '09 09:10

balaji


1 Answers

To load the assembly, you would do this:

Assembly assembly = Assembly.LoadFile(@"test.dll");

This assumes you have the assemblies on disk as files. If you don't, like if you get them from a database as a byte array, there are other methods on the Assembly that will help you give you an Assembly object after loading it.

To iterate through all the classes in the assembly, you would do this:

Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass)
    {
        ...
    }
}

To find the OnStart static method, you would do this:

Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass)
    {
        MethodInfo method = type.GetMethod("OnStart",
            BindingFlags.Static | BindingFlags.Public);
        if (method != null)
        {
            ...
        }
    }
}

To call the method, you would do this:

Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass)
    {
        MethodInfo method = type.GetMethod("OnStart",
            BindingFlags.Static | BindingFlags.Public);
        if (method != null)
        {
            method.Invoke(null, new Object[0]); // assumes no parameters
            break; // no need to look for more methods, unless you got multiple?
        }
    }
}

If you need to pass arguments to the method, you would put them in an object array:

Object[] arguments = new Object[] { arg1, arg2, arg3 ... };
method.Invoke(null, arguments);

The above code can be collapsed to the following by using Linq to find the method for us:

Assembly assembly = Assembly.LoadFile(@"test.dll");
var method = (from type in assembly.GetTypes()
              where type.IsClass
              let onStartMethod = type.GetMethod("OnStart",
                  BindingFlags.Static | BindingFlags.Public)
              where onStartMethod != null
              select onStartMethod).FirstOrDefault();
if (method != null)
{
    method.Invoke(null, new Object[0]); // assumes no parameters
}
like image 169
Lasse V. Karlsen Avatar answered Sep 17 '22 12:09

Lasse V. Karlsen