簡體   English   中英

在運行時加載程序集 .NET 6

[英]Load Assembly at Runtime .NET 6

我們正處於將 c# Winforms 應用程序從 .NET Framework 轉換為 .NET 6 的開始階段。我們可以讓項目在 .NET 6 中構建和運行,但是當涉及到動態加載的程序集時,我們遇到了問題。 我們可以加載程序集,但嘗試訪問其中的自定義 class 會返回 null。我在兩個較小的項目中重新創建了這個場景作為示例。

解決方案 1/項目 1 - 要加載到主應用程序中的程序集的代碼。 這是創建 TestAssembly.dll 的 class 庫

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

    }
}

解決方案 2/項目 1 - 這是主應用程序解決方案中的項目和 class。 這是創建 Custom.TestAssembly.dll 的 class 庫

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

解決方案 2/項目 2 - 在窗體上放置了一個按鈕。 單擊它時,應該加載程序集,它是。 但是,嘗試從程序集中提取 class 總是會返回 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??

        }

    }
}

只是想了解我所缺少的。 有什么想法嗎? 或者在 .NET 6 中加載運行時程序集並訪問其中的類的更好方法?

您是否參考了解決方案 2/項目 1? 由於它們具有相同的程序集名稱Custom.TestAssembly ,如果已在 memory 中加載,運行時將不會再次加載它。

但是,您可以在不同的AssemblyLoadContext下加載它, MSDN 上也有一個示例

此外,您可能想看看DotNetCorePlugins ,它負責程序集加載、重新加載、隔離、共享類型和依賴項解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM