Question

I'm having some trouble instantiating a class defined in a DLL file using Reflection. Even though the code seems fine I get TargetInvocationException on Activator.CreateInstance. The code goes as follows (for now only a single DLL is available):

public Comparator() 
{
    string[] filePaths = Directory.GetFiles(@".\Extensions");
    for (int i = 0; i < filePaths.Length; ++i)
    {
        var asm = Assembly.LoadFrom(Path.GetFullPath(filePaths[i]));

        if (asm != null)
        {
            foreach (Type currType in asm.ExportedTypes)
            {
                if (!currType.IsAbstract && currType.IsPublic && typeof(SorterBase).IsAssignableFrom(currType))
                {
                    Debug.WriteLine(currType); //outputs: BubbleSort.Sorter
                    var instance = Activator.CreateInstance(currType); //TargetInvocationException
                }
            }
        }
    }
}

This is the class I'm trying to instantiate:

using SortingLibrary;
using SortingFunctions;
namespace BubbleSort
{
    public class Sorter : SorterBase //SorterBase is an abstract class defined in SortingLibrary
    {
        public Sorter()
        {
            SetFunction(Sorting.BubbleSort);
            AlgorithmName = @"Bubble Sort";
        }
    }
}

The only way I managed to prevent that problem from happening was to add the loaded .dll to references before compilation. The problem is, that normally during compile time there is no way of telling what libraries will need to be loaded. What am I missing here?

The entire solution (although a bit messy at the moment) can be downloaded here: http://nazr.in/rOD

Any help will be really appreciated! Thank you in advance.

Was it helpful?

Solution

You have to copy all dependencies to the folder Extensions. In your case you are missing SortingFunctions.dll which BubbleSort.dll depends on. It is reflected in the Inner Exception.

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