Using .net6 or .net7, I can't make a dynamically loaded class library (read plugin) load the System.IO.Ports.dll. I'm using VS2022, but had the same problem on .net5 and VS2019. I'm only using Windows.
I have dropped some demonstration code here: https://github.com/JanJorgensen/Net5AddonLoadProblemDemo
The application loads the plugin like this:
public static void LoadAndActivateTheAddon()
{
var assembly = Assembly.LoadFrom("TheAddon.dll");
var type = assembly.GetExportedTypes().Where(t => t.Name == "AddonMain").FirstOrDefault();
object obj = Activator.CreateInstance(type);
var addon = obj as IAddon;
addon.Action(); // Call a method in the loaded plugin object.
}
Exception thrown when trying to create instance of SerialPort class is: System.PlatformNotSupportedException, "System.IO.Ports is currently only supported on Windows."
In .Net Framework (2 through 4.5), it worked perfectly. Maybe because that was only for Windows.
If I create a .net application (console, WinForms or WPF) and use System.IO.Ports directly from that, it works perfectly.
But while I'm unfortunately not a .net pro, I think there's something I don't know about building and distributing .net5-7 applications for Windows.
In the output folder, a 'runtimes' folder is created when building, with the Ports assembly in a version for different target systems.
So why can't the dynamically loaded class library load the System.IO.Ports.dll? In a deployed installation it doesn't work either. It seems the plugin assembly should be configured to use the .net7 version of the assembly when on Windows.
I have a dirty solution at the moment, where I add the library as a dependency in my top level application, just to make sure it is loaded, making the plugin work. But that's so ugly and should not be necessary.
I posted the question before, but back then I didn't have the example code.
I'm sure the solution is simple, but ...
I rely on all you good people to help me with this. Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire