在另一个 AppDomain 中创建类型的实例 [英] CreateInstance of a Type in another AppDomain

查看:27
本文介绍了在另一个 AppDomain 中创建类型的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是我有一个创建 AppDomains 的 .net 应用程序(假设是一个控制台应用程序).然后它需要在该 AppDomain 中的类型上创建实例和调用方法.每个 AppDomain 都有一个特定的目录,它的依赖项应该在哪里,它不在(或什至靠近)Console Apps 目录下.这是我的简单代码:

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

对 CreateInstanceFrom 的调用导致 FileNotFoundExcepotion.FusionLog显示搜索到的目录是Console应用目录.它不包括从 AppDomain 设置的搜索文件夹 - 在baseDirecory"变量中.

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.

我做错了什么?还有其他方法可以执行位于另一个 AppDomain 中的代码吗?

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

谢谢...

推荐答案

一种解决方法是将完整路径传递给 .CreateInstanceFrom 调用:

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

这篇关于在另一个 AppDomain 中创建类型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆