首页 > 解决方案 > 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,但不了解类型。

我该如何解决这个问题?谢谢!

交叉张贴在这里:https ://social.msdn.microsoft.com/Forums/azure/en-US/59b119d8-1e51-4460-bf86-01b96ed55b12/how-can-i-create-an-appdomain-in-azure- functions?forum=AzureFunctions&prof=必需

标签: c#.netazureazure-functionsappdomain

解决方案


在这种情况下,“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下添加问题。


推荐阅读