简体   繁体   中英

Load Assembly at Runtime .NET 6

We are in the beginning stages of converting a c# Winforms App from .NET Framework to .NET 6. We can get the project to build and run in .NET 6, but when it comes to a dynamically loaded assembly, we are having issues. We can get the assembly to load but attempting to access the custom class within it returns a null. I recreated this scenario in two smaller projects as an example.

Solution 1/Project 1 - The code for the assembly to be loaded into the main application. This is a class library that creates the TestAssembly.dll

namespace Custom.TestAssembly
{
    public class TestClass : CallingModule
    {
        public override object GetValue()
        {
            return "Hello World";
        }

    }
}

Solution 2/Project 1 - This is a project and class within the main application's solution. This is a class library that creates the Custom.TestAssembly.dll

namespace Custom.TestAssembly
{
    public class CallingModule
    {
        public virtual object? GetValue()
        {
            return null;
        }
    }
}

Solution 2/Project 2 - A button has been placed on a form. When it is clicked, the assembly should be loaded, which it is. However, attempting to extract the class from the assembly always returns a NULL.

Form1.cs

using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Loader;


namespace TestCallingApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Assembly dynamicAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(@"C:\LocationOf\TestAssembly.dll");
            Module customizationModule = dynamicAssembly.GetModule("TestAssembly.dll");
            Type customClientModule = customizationModule.GetType("Custom.TestAssembly.TestClass");  //THIS RETURNS A NULL??

        }

    }
}

Just trying to understand what I am missing. Any thoughts? Or a better way to load runtime assemblies and access classes within them in .NET 6?

Did you reference Solution 2/Project 1? Since they have the same assembly name Custom.TestAssembly , the runtime will not load it again if already loaded in memory.

You can, however, load it under a different AssemblyLoadContext , there's an example on MSDN as well.

Also, you may want to take a look at DotNetCorePlugins , which takes care of assembly loading, reloading, isolation, shared type, and dependency resolving.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM