views:

59

answers:

2

I have several streams with an assembly and its used dlls. How can I load them into an AppDomain and execute the main assembly? I'd rather not save the files to disk if it can be avoided.

A: 

You can use obtain the assembly through the following mechanism.

Assembly myAssembly = Assembly.Load(<your raw file stream>);

You can register for the following event and handle the same to serve requested types coming from your custom assemblies:

AppDomain.CurrentDomain.TypeResolve += new ResolveEventHandler(CurrentDomain_TypeResolve);

static Assembly CurrentDomain_TypeResolve(object sender, ResolveEventArgs args)
    {
        Type  resolvedType =  myAssembly.GetType( args.Name, false);
    }

Unfortunately any type loaded in your program would end up here, so you might want to build in some caching mechanism to store type info

Bharath K
I just tried it, but it doesn't call the handler. Instead it crashes when I invoke the main method of the loaded and instantiated main assembly. (TargetInvocationException: IOException: Cannot locate resource 'mainwindow.xaml'.)The application runs fine when I load it directly.
Tamschi
This would not work if your assembly has embedded resources since only type resolution is done in the above code. If you can move these resources, it should work fine. Or you can use Assembly.GetManifestResourceInfo to fetch resources from this assembly separately
Bharath K
I added resource resolution to my code, but the handler is only called for resources in the loader assembly. Also, the xaml file in the exception seems to be missing in the assemblies resources. (I'm using GetManifestResourceNames() to list the resources.)
Tamschi