c# - Azure 函数中的 AppDomain
问题描述
我试图在 Azure Functions 中创建一个 AppDomain 来运行不受信任的代码。创建域似乎工作正常,但是当我尝试加载程序集时,似乎它们加载不正确。
首先我尝试了一个简单的 AppDomain:
public class Sandboxer
{
public void Run()
{
AppDomain newDomain = AppDomain.CreateDomain("name");
var obj = newDomain.CreateInstance(typeof(OtherProgram).Assembly.FullName, typeof(OtherProgram).FullName).Unwrap();
}
}
public class OtherProgram : MarshalByRefObject
{
public void Main(string[] args)
{
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
foreach (var item in args)
Console.WriteLine(item);
}
}
我有一个错误
“System.IO.FileNotFoundException:无法加载文件或程序集‘Sandboxer,Version=1.0.0.0,Culture=neutral,PublicKeyToken=2cd9cb1d6fdb50b4’或其依赖项之一。系统找不到指定的文件。”
然后我尝试将 appliactionBase 设置为包含我的 dll 的文件夹。
public class Sandboxer
{
public void Run()
{
var location = typeof(OtherProgram).Assembly.Location;
AppDomainSetup ads = new AppDomainSetup();
ads.ApplicationBase = Path.GetDirectoryName(location);
AppDomain newDomain = AppDomain.CreateDomain("name", null, ads);
var obj = newDomain.CreateInstance(typeof(OtherProgram).Assembly.FullName, typeof(OtherProgram).FullName).Unwrap();
var other = obj as OtherProgram;
var other2 = obj as MarshalByRefObject;
}
}
public class OtherProgram : MarshalByRefObject
{
public void Main(string[] args)
{
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
foreach (var item in args)
Console.WriteLine(item);
}
}
在这种情况下,“other”在 Run() 方法的末尾为 null,但“other2”是一个 __TransparentProxy。似乎它正在查找并加载 dll,但不了解类型。
我该如何解决这个问题?谢谢!
解决方案
在这种情况下,“other”在 Run() 方法的末尾为 null,但“other2”是一个 __TransparentProxy。似乎它正在查找并加载 dll,但不了解类型。
根据您的描述,我可能会遇到类似的问题,我尝试创建一个控制台应用程序来检查这个问题,发现代码可以在控制台应用程序下按预期工作。
对于 Azure 函数,obj as OtherProgram
始终返回 null。然后我尝试OtherProgram
在当前域下实例化如下:
var obj=AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(typeof(OtherProgram).Assembly.Location, typeof(OtherProgram).FullName);
OtherProgram op = obj as OtherProgram;
if (op != null)
op.PrintDomain(log);
上面的代码可以按预期工作,但是我没有找到为什么新的AppDomain下的对象总是返回null。您可以尝试在Azure/Azure-Functions下添加问题。
推荐阅读
- django-models - 在 ListView 中编辑模型
- here-api - 如何组合 JS API URL 调用?
- azure - 是否可以使用 Azure 自动化 Runbook 删除另一个 Runbook 输出(Azure 文件共享快照)?
- angular - 如何以角度获得反应形式的价值组件?
- nativescript - 进度指示器在 android 平台 nativescript 中的 TabView 内没有停止
- c# - 如何在 MongoDB 的 Linq 查询中使用 .Contains 和 ToLower?
- react-native - React Native Pan Responder 为单个动态视图设置动画
- angular - 如何按选定值过滤数据?
- c++ - 如何在字符串c ++中附加Hexa十进制值?
- php - PHP cURL POST 返回 bool(false)