CodexBloom - Programming Q&A Platform

Issues with Dynamically Loading Assemblies in .NET 6 Causing TypeLoadException

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-06-06
c# .net-6 dynamically-loading-assemblies C#

I've encountered a strange issue with After trying multiple solutions online, I still can't figure this out... I'm facing a `TypeLoadException` when trying to dynamically load an assembly in my .NET 6 application. The assembly is being loaded from a plugin directory, and I’m using the `Assembly.LoadFrom` method. Here's the code snippet that is causing the issue: ```csharp string pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins", "MyPlugin.dll"); Assembly pluginAssembly = Assembly.LoadFrom(pluginPath); ``` The exception message reads: `Could not load type 'MyPlugin.MyClass' from assembly 'MyPlugin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.` I’ve checked that the class `MyClass` is public and that the DLL is indeed in the specified directory. I also have the following in my `appsettings.json` file, to include the plugin path: ```json { "PluginPath": "./Plugins" } ``` I've made sure that the `MyPlugin.dll` is compiled for the same framework version (net6.0) and the project references are correct. Additionally, I’m using the `AssemblyResolve` event to handle dependencies, but I’m not sure if I’ve set it up correctly. Here’s what I tried: ```csharp AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { string assemblyPath = Path.Combine(pluginPath, new AssemblyName(args.Name).Name + ".dll"); return Assembly.LoadFrom(assemblyPath); }; ``` Despite this, the exception persists. I’ve also verified that `MyClass` implements an interface from my main application, and the interface signature hasn’t changed. Any insights on why I'm encountering this `TypeLoadException` and how to properly load the assembly with the required types would be greatly appreciated. I'm working in a Linux environment. Thanks for your help in advance! This is part of a larger REST API I'm building. Thanks for your help in advance!