Activator.CreateInstance throws an exception

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

c#
reflection
activator
asked on Stack Overflow Sep 1, 2013 by SexyMF

3 Answers

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

answered on Stack Overflow Sep 1, 2013 by Jeroen van Langen • edited May 23, 2017 by Community
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);
answered on Stack Overflow Sep 1, 2013 by dcastro
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.

answered on Stack Overflow Sep 1, 2013 by mp3ferret

User contributions licensed under CC BY-SA 3.0