I'm working on a service which needs different assemblies, but at compile time we don't know which ones. Therefore I want to dynamically load an unload different assemblies. I had the loading working with this code,
static private void ExecuteAssemblyMethod(string taskName, string className, string method)
{
//load assembly in parent application domain, the assembly can not be unloaded.
var task = Assembly.LoadFrom($"tasks\\{taskName}.exe");
var myType = task.GetType($"{taskName}.{className}");
MethodInfo myMethod = myType.GetMethod(method);
object obj = Activator.CreateInstance(myType);
myMethod.Invoke(obj, null);
}
But I found out the assembly can only be unloaded by unloading the appdomain. Therefore it needs to run in a different appdomain which can be unloaded. But I do not get this working. I tried the code below, but it does not work because CreateInstanceFrom return type objecthandle and not object as I expected.
static private void ExecuteAssemblyMethodInAppDomain(string taskName, string className, string method)
{
//create child domain and load assembly within it. the appdomain can than be unloaded.
var dom = AppDomain.CreateDomain("taskDomain");
var task = dom.CreateInstanceFrom($"tasks\\{taskName}.exe", $"{ taskName}.{ className}");
Type myType = task.GetType();
MethodInfo myMethod = myType.GetMethod(method);
myMethod.Invoke(task, null);
AppDomain.Unload(dom);
}