Azure 函数中的 AppDomain

AppDomain in Azure Function

我试图在 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 : Could not load file or assembly 'Sandboxer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2cd9cb1d6fdb50b4' or one of its dependencies. The system cannot find the file specified."

然后我尝试将 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" 在 运行() 方法的末尾为 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=required

这就是我在传统 .NET 应用程序中的做法,应该适用于 Azure Functions:

  1. 在新创建的 AppDomain
  2. 上注册 AppDomain.AssemblyResolve 事件
  3. 在事件处理程序中,使用 Function Directory / Function App Directory 解析程序集路径以指向 bin 文件夹

In this case, "other" is null at the end of the Run() method, but "other2" is a __TransparentProxy. It seems like it is finding and loading the dll, but doesn't understand the type.

根据你的描述,我可能遇到了类似的问题,我尝试创建一个控制台应用程序来检查这个问题,发现代码在控制台应用程序下可以正常运行。

对于 Azure 函数,obj as OtherProgram 总是 returns 空。然后我尝试在当前域下实例化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下的对象总是returns null。您可以尝试在 Azure/Azure-Functions.

下添加问题

AppDomains 不能与 Azure Functions 一起使用。为了在 Azure Functions 中正确沙盒代码,您必须创建一个新的 Azure Functions 应用程序和 运行 那里的代码。

如果您允许用户编写脚本,您可以使用另一种语言,例如 Lua,它允许简单的沙盒。