0

I need to load several .dll files in a separate AppDomain, do some operations with them and unload the AppDomain. I can do that through CreateInstanseFrom but I need to know the name of the type.

If I get all the types in the given assembly, I can filter out mine.

I can get all the types through reflection, but that only works for the current AppDomain, right? It's no use loading the files first in the current domain, get the types and load them into the custom domain.

Is there a method to load an assembly from a file to a custom app domain?

Michael
  • 57,169
  • 9
  • 80
  • 125
Bonnev
  • 947
  • 2
  • 9
  • 29

1 Answers1

1

Instead of trying to use a class from one of the target assemblies in the CreateInstanceFrom/CreateInstanceFromAndUnwrap call, use a class of your own. You can create that well-known class inside the appdomain and call to a well-known method. Inside that well-known method, process the assemblies.

// This class will be created inside your temporary appdomain.
class MyClass : MarshalByRefObject
{
    // This call will be executed inside your temporary appdomain.
    void ProcessAssemblies(string[] assemblyPaths)
    {
        // the assemblies are processed here
        foreach (var assemblyPath in assemblyPaths)
        {
            var asm = Assembly.LoadFrom(assemblyPath);
            ...
        }
    }
}

And use it like so to process the assemblies:

string[] assembliesToProcess = ...;

// create the temporary appdomain
var appDomain = AppDomain.CreateDomain(...);
try
{
    // create a MyClass instance within the temporary appdomain
    var o = (MyClass) appDomain.CreateInstanceFromAndUnwrap(
        typeof(MyClass).Assembly.Location,
        typeof(MyClass).FullName);

    // call into the temporary appdomain to process the assemblies
    o.ProcessAssemblies(assembliesToProcess);
}
finally
{
    // unload the temporary appdomain
    AppDomain.Unload(appDomain);
}
Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
  • When loading my assemblies, i get a Could not load file or assembly '...' or one of its dependencies. The system cannot find the file specified. We're talking about dlls like shell32 and wmplib which i've added but are not .net assemblies. Since my assemblies are dependent on them, is there a way i can load "unsafe" assemblies? UnsafeLoadFrom doesn't work. – Bonnev Jul 13 '15 at 21:00
  • .dlls are not necessarily assemblies, and assemblies are not necessarily .dlls. You are trying to work with with unmanaged .dlls from a managed process. You'd have to tell us more about what you're trying to accomplish before I could help. However, [LoadLibrary](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175.aspx) is the Win32 API that is used to load .dlls. Reading the documentation may help. – Michael Gunter Jul 13 '15 at 22:37