lundi 12 octobre 2020

Failing to load project through Reflection

I'm trying to load a WpfCustomControlLibrary at runtime with Reflection but it throws a System.IO.FileNotFoundException when it has to access System.Data.SQLite.

The idea of the current setup is that the running application isn't aware of the exact control it has to load, as long as it matches a specific Interface.

At this point i'm trying to load the project directly from the Debug folder of the WpfCustomControlLibrary to be sure all referenced libraries exist in the same directory as the project itself.

This is how I currently try to load the control:

UserControl myControl = null;
Assembly asm = Assembly.LoadFrom(@"SomePath\bin\Debug\ControlLibrary.dll");

Type[] types = null;
try
{
    types = asm.GetTypes();

    if (types != null)
    {
        foreach (var t in types.Where(t => t != null))
        {
            if (t.Name == "MyControl")
            {
                myControl = Activator.CreateInstance(t) as UserControl;

                Type[] ifs = t.GetInterfaces();

                var project = ifs.FirstOrDefault(x => x == typeof(IMyInterface));

                if(project != null)
                {
                    IMyInterface actualProject = myControl as IMyInterface;

                    //Creates a new database when none exists.
                    actualProject.Init(@"Data Source=.\Database.db;Version=3;");
                    actualProject.Start();
                }

                break;
            }
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show($"Failed to load Project: {ex}");
}

When I load MyControl as a referenced project, it doesn't have any problems accessing System.Data.SQLite.

the actualProject.Init method basically runs this code:

// Create database if it doesn't exist yet
foreach (string sub in this.ConnectionString.Split(';'))
{
    string prefix = "Data Source=";
    if (sub.Contains(prefix))
    {
        string name = sub.Remove(0, prefix.Length);

        if (!File.Exists(name))
        {
            SQLiteConnection.CreateFile(name);
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire