CreateInstance of a Type in another AppDomain
Asked Answered
S

2

3

My scenario is that I have a .net application (let's say a Console App) that creates AppDomains. It then needs to create instances and call methods on Types that are in that AppDomain. Each AppDomain has a specific directory where are it's dependecies should be, which is not under (or even near) the Console Apps directory. Here's my simple code:

string baseDirectory = "c:\foo"; // <- where AppDomain's dependecies 

// set up the app domain
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationName = DateTime.Now.ToString("hh:MM:ss:ffff");
setup.ApplicationBase = baseDirectory;
setup.PrivateBinPath = baseDirectory;

// create app domain
AppDomain domain = AppDomain.CreateDomain(
    name,
    AppDomain.CurrentDomain.Evidence,
    setup );

// instantiate Type from an assembly in that AppDomain
ObjectHandle handle = domain.CreateInstanceFrom(
    "SampleClassLibrary.dll", // <- exists in "c:\foo" 
    "SomeClassInTheDll" ); 

The call to CreateInstanceFrom results in a FileNotFoundExcepotion. The FusionLog shows that the directories it searchedwere the Console applications directories. It did not include search folders that were set from the AppDomain - in the "baseDirecory" variable.

What am I doing wrong? Is there another way to execute code that lives in another AppDomain?

Thanks...

Steading answered 16/1, 2010 at 0:50 Comment(2)
Please read my blog on cross-AppDomain Communication blog.vcillusion.co.in/…Jaimeejaimes
Maybe try using AssemblyResolve to resolve the assembly at runtime.Jaimeejaimes
B
3

One workaround would be to pass the full path to the .CreateInstanceFrom call:

ObjectHandle handle = domain.CreateInstanceFrom( 
    baseDirectory + @"\SampleClassLibrary.dll", // <- exists in "c:\foo"  
    "SomeClassInTheDll" );
Boyhood answered 16/1, 2010 at 1:33 Comment(3)
Just providing a fully qualified path to the dll did the trick, at least I was able to load that type. Seems odd that the AppDomain does look in "baseDirectory" for that dll though. I wonder if there's going to be issues if that dll has references to other dlls which are in that directory. I'l test it out and see. Thanks BruceSteading
Just as I thought, solution above doesn't work. It's like the AppDomain can't find any of it's dependent dlls since the directory it's looking in is the Console Apps directory list, not the AppDomains... Any ideas? This can't be this hard?Steading
Figured out that using the AssemblyResolve handler did the trick.Steading
F
0

I can't say what's wrong with your code, as it looks like it should work. When I have doen this, however, I've made a helper to do the work. Roughly like this:

public class Loader
{
    public void Load(string typename)
    {
        // ....
    }
}

Loader l = (Loader)domain.CreateInstanceAndUnwrap("Loader");
l.Load("SomeClassInTheDll");
Filmer answered 16/1, 2010 at 1:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.