Run a base class method from a derived class on another assembly dynamically

450 views Asked by At

I'm trying to call from another assembly a base class static method from it's derived class dynamically, using the following code:

Assembly executingAssembly = Assembly.GetExecutingAssembly();

Assembly objectAssembly = 
    Assembly.Load(executingAssembly.GetReferencedAssemblies().
    Where(a => a.Name == "WebDelightBLL").FirstOrDefault());

Type myType = objectAssembly.GetType("WebDelightBLL.Ingredient");

MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public | BindingFlags.Static);

object myInstance = Activator.CreateInstance(myType);

dgvResultsRES.DataSource = myMethod.Invoke(myInstance, null);

Code in the Dll as following:

public class BaseClass<DerivedClass>
{
    public static Type MyType()
    {
        return typeof(DerivedClass);
    }
    public static string Prefix()
    {
        return "Sp" + MyType().Name;
    }
    public static DataTable GetAll()
    {
        try
        {
            DataTable dt = GetSP(Connection.connectionString(),
              Prefix() + "GetAll", 5);
            return dt;
        }
        catch (Exception)
        {
            throw;
        }
    }
}
public class Ingredient : BaseClass<Ingredient>
{
    public string SayHello()
    {
        return "Hello, World!"; //Just to exemplify a point
    }
}

But I always get "Object reference not set to an instance of an object"

If I try to call 'SayHello()' for instance I get no error.

Is this even possible?

Update:

By adding BindingFlags.FlattenHierarchy as indicated by Creep it worked like a charm. Working code as follows:

        Type myType = objectAssembly.GetType("WebDelightBLL.Ingredient");

        MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public 
            | BindingFlags.Static | BindingFlags.FlattenHierarchy);

        //object myInstance = Activator.CreateInstance(myType); <-- not needed.

        dgvResultsRES.DataSource = myMethod.Invoke(null, null);
2

There are 2 answers

3
Creep On

Since your method is static in your base class, it does not belong to its child.
The following code will work:

Type myType = objectAssembly.GetType("WebDelightBLL.BaseClass");
MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public | BindingFlags.Static);
myMethod.Invoke(null, null);
1
mrogal.ski On

You're trying to invoke static method so you cannot specify instance of the object ( to get rid of "Object reference not set to an instance of an object" error ). And since this method doesn't have any parameters you can just create an empty parameter array

MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public | BindingFlags.Static);
// dont need this
//object myInstance = Activator.CreateInstance(myType);

//dgvResultsRES.DataSource = myMethod.Invoke(myInstance, null);
dgvResultsRES.DataSource = myMethod.Invoke(null, new object[0]);