Reputation: 4512
I have program, which creates AppDomain
, loads assembly prelude
within it and then unloads AppDomain
. At the end program lists assemblies from default appdomain. It's simplified version of program. In next versions prelude.dll
will be changed in runtime and continiously executed/unloaded with appdomain.
namespace appdomaintest
{
class Program
{
static void log_assemblies(AppDomain domain)
{
foreach (var item in domain.GetAssemblies())
{
Console.WriteLine($"{domain.FriendlyName} : {item.FullName}");
}
}
static void Main(string[] args)
{
{
var prelude_domain = AppDomain.CreateDomain("PreludeDomain#1", null, null);
var asm = prelude_domain.Load(new System.Reflection.AssemblyName("prelude"));
var myint = prelude_domain.CreateInstanceAndUnwrap("prelude", "prelude.MyInt");
myint.GetType().GetMethod("show").Invoke(myint, new object[0]);
AppDomain.Unload(prelude_domain);
Console.WriteLine("AppDomain was unloaded");
}
log_assemblies(AppDomain.CurrentDomain);
}
}
}
Here is content of prelude.dll
public class MyInt : MarshalByRefObject
{
public MyInt()
{
Console.WriteLine($"MyInt was constructed in {AppDomain.CurrentDomain.FriendlyName}");
}
public void show()
{
Console.WriteLine($"show in {AppDomain.CurrentDomain.FriendlyName}");
}
}
Here is output of program:
MyInt was constructed in PreludeDomain#1
show in PreludeDomain#1
AppDomain was unloaded
appdomaintest.exe : mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
appdomaintest.exe : appdomaintest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
appdomaintest.exe : prelude, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Unfortunately I discovered that my default appdomain contains prelude.dll
assembly. As I understand it remains until end of execution of my program. Is there any way to prevent loading it to default appdomain? In future versions prelude.dll
will be repeatedly loaded/unloaded (its metadata also will be modified). That's why that behaviour is not suitable for my purposes.
It seems like for me that creation proxy object may lead to loading metadata to default domain. But how can I unload them?
Upvotes: 0
Views: 187
Reputation: 7526
It will remain, yes. There is no way around it, because this is just not possible which microsoft stated in here: https://learn.microsoft.com/en-us/dotnet/framework/app-domains/how-to-unload-an-application-domain.
Use interprocess communication with another process. You can start process and load anything inside it, until it becomes bloated, after which you just kill it and start it over.
One benefit you get from this - no one will crash your app accidentally calling something unsafe in this library.
Upvotes: 1