Prepare two projects
The first is the console
The second project is the class library
There is only one example class in the class library project
Generate the code of the class library into a dll
And set the property to copy to the output directory
using System.Runtime.Loader;
var domain = new AssemblyLoadContext("DomainServer", true);
var assembly = domain.LoadFromAssemblyPath(Path.Combine(AppContext.BaseDirectory, "DomainServer.dll"));
foreach (var context in AssemblyLoadContext.All)
{
Console.WriteLine("当前存在的程序集:"+context.Name);
}
Console.WriteLine("-------------------------");
domain.Unload();
foreach (var context in AssemblyLoadContext.All)
{
Console.WriteLine("当前存在的程序集:" + context.Name);
}
Console.ReadKey();
Write the code into the Program class Since the project is created using .net7, it adopts top-level syntax and has no main method
Then execute the program
We see that when loading the program, there are two assemblies in our project
When the current Unload unloads the assembly, there is only one assembly in our project
Create an AssemblyLoadContext object using new AssemblyLoadContext("DomainServer", true);
The second argument is true to enable uninstallation; otherwise, false. The default value is false because of the performance penalty of enabling offloading.
This unload will only unload all assemblies loaded in AssemblyLoadContext
We can also subscribe to the uninstall event so we know that those assemblies were successfully uninstalled
using System.Runtime.Loader;
var domain = new AssemblyLoadContext("DomainServer",true);
var assembly = domain.LoadFromAssemblyPath(Path.Combine(AppContext.BaseDirectory, "DomainServer.dll"));
foreach (var context in AssemblyLoadContext.All)
{
Console.WriteLine("当前存在的程序集:"+context.Name);
}
Console.WriteLine("-------------------------");
domain.Unloading += context =>
{
Console.WriteLine("当前卸载的程序集:"+string.Join(',', context.Assemblies.Select(x => x.FullName)));
};
domain.Unload();
foreach (var context in AssemblyLoadContext.All)
{
Console.WriteLine("当前存在的程序集:" + context.Name);
}
Console.ReadKey();
Execution effect:
Ok, let's introduce it here!
Methods that can be used in versions above .Net 6
Technology sharing group: 737776595
Sharing from token