Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Refelection.Assembly.CreateInstance broken in .NET 4.0

We upgraded from .NET 3.5 to .NET 4.0 and now System.Refelection.Assembly.CreateInstance does not appear to be working. Has anyone else had this problem? Is there a way to fix it? Below is an example of how we are loading the asembly. It returns a null value. No exception. It's a .NET Assembly registered in the GAC. It is not a COM object.

Assembly assembly = Assembly.LoadWithPartialName("AssemblyName");
object instance = assembly.CreateInstance("Namespace.Class",
                        false,
                        BindingFlags.CreateInstance,
                        null,
                        null, null, null);

I narrowed down the cause of the problem. My class A that I am trying to create inherits from class B. Class B is defined as public abstract class B. Class B contains most of the logic with one abstract method that class A defines. Similarly I have another class C that inherits from Class B that has a different definition for the method. Basically refactoring to share common logic. This worked in .NET 3.5 but in .NET 4.0 I finally narrowed down the exception to be "{"Cannot create an abstract class."}".

public abstract class A
{
  public string InvokeUI() 
  {
    //some logic
    DisplayUI();
  }

  protected abstract void DisplayUI();
}

public class B : A
{
  protected override DisplayUI()
  {
    Some logic;
  }
}
like image 850
Tammy Avatar asked Jul 15 '26 14:07

Tammy


2 Answers

With the Activator it works fine with .net Framework 4.0 compiled with the following platforms (x86/x64/Any CPU):

using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var ass = Assembly.Load("ConsoleApplication1");
            var type = ass.GetType("ConsoleApplication1.Test");
            var obj = Activator.CreateInstance(type);
            Console.ReadLine();


        }
    }

    public class Test    {        }
}
like image 157
CaptainPlanet Avatar answered Jul 19 '26 00:07

CaptainPlanet


You have to use fusion.dll library to read the GAC. Once you find the “Full Assembly Name” you can use Reflection.[Assembly].Load() instead of Reflection.[Assembly].LoadWithPartialName(). There is the article I wrote that explains what needs to be done:

http://www.codeproject.com/Articles/485145/Late-Binding-to-NET-objects-in-NET-4-0

like image 25
Igor Krupitsky Avatar answered Jul 19 '26 01:07

Igor Krupitsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!