Question

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

Was it helpful?

Solution 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);

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top