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.To开发者_JAVA技巧String("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...
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" );
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");
精彩评论