Search code examples
c#appdomaincreateinstance

CreateInstance of a Type in another AppDomain


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...


Solution

  • 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" );