jeudi 5 janvier 2017

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

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?





Aucun commentaire:

Enregistrer un commentaire