0

I have this class:

public class PlaceLogicEventListener : ILogicEventListener
{

}

I have this code trying to create an instance by reflection:

public ILogicEventListener GetOne(){
    Type type = typeof (PlaceLogicEventListener);
    return  (ILogicEventListener)Activator.CreateInstance(type.Assembly.Location, type.Name);
}

I am getting the following exception:

System.TypeInitializationException : The type initializer for 'CrudApp.Tests.Database.DatabaseTestHelper' threw an exception.
  ----> System.IO.FileLoadException : Could not load file or assembly 'C:\\Users\\xxx\\AppData\\Local\\Temp\\vd2nxkle.z0h\\CrudApp.Tests\\assembly\\dl3\\5a08214b\\fe3c0188_57a7ce01\\CrudApp.BusinessLogic.dll' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

I am calling the GetOne() from the tests dll. The code of PlaceLogicEventListener and the mothod GetOne() are both in the same assembly CrudApp.BusinessLogic.dll

SexyMF
  • 9,064
  • 25
  • 88
  • 161

3 Answers3

3

This could be because you need the full name of the type.

try: return (ILogicEventListener)Activator.CreateInstance(type.Assembly.Location, type.FullName);

Also check this thread: The type initializer for 'MyClass' threw an exception

Community
  • 1
  • 1
Jeroen van Langen
  • 18,289
  • 3
  • 33
  • 50
2

You're passying type.Name as a parameter, but PlaceLogicEventListener only has an implicit parameterless constructor.

Try:

Type type = typeof (PlaceLogicEventListener);
Activator.CreateInstance(type);
dcastro
  • 59,520
  • 20
  • 126
  • 147
2

You were also passing in the wrong assembyly name - it needed the display name. So :

        Type type = typeof(PlaceLogicEventListener);
        var foo = (ILogicEventListener)Activator.CreateInstance(type.Assembly.FullName, type.FullName).Unwrap();

Should do it and also unwrrap the ObjectHandle passed back from CreateInstance.

mp3ferret
  • 1,123
  • 10
  • 15