运行 .NET 5 中 AppDomain 中的操作

Run action in AppDomain in .NET 5

我正在将应用程序从 .NET Framework 迁移到 .NET 5.0。

在我之前的实现中,我从外部源动态读取程序集,然后将它们加载到不同的 AppDomains,然后 运行通过 CrossAppDomainDelegate 执行一个操作。

每个程序集 运行 的代码示例:

var setup = new AppDomainSetup
{
    ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
};

var domain = AppDomain.CreateDomain($"MyDomain", null, setup);
var del = new CrossAppDomainDelegate(action); // The action I'm running

domain.DoCallBack(del);

在 .NET 5.0 中,我仍然可以创建域(即使我不能像以前那样使用设置)但是我似乎无法找到通过委托来 运行 操作的方法,因为不再支持 CrossAppDomainDelegate

关于如何实现这一点有什么想法吗?有可能吗? 如果没有,还有什么方法可以实现此功能?

考虑将 AppDomain class 的 CreateInstanceAndUnwrap 方法与跨应用委托的 MarshalByRefObject 代理实现结合使用,例如:


public interface IRuntime
{
    object Run<T>(Expression<Func<T>> del);
}


public class Runtime : MarshalByRefObject, IRuntime
{
    public object Run<T>(Expression<Func<T>> del)
    {
        return del.Compile().Invoke();
    }
}


void Main()
{
    AppDomain childDomain = null;
    try
    {


        // Create the child AppDomain 
        childDomain = AppDomain.CurrentDomain;
        // AppDomain.CreateDomain("Your Child AppDomain"); //supported? NET5.0

        // Create an instance of the runtime in the second AppDomain. 
        // A proxy to the object is returned.
        IRuntime runtime = (IRuntime) childDomain.CreateInstanceAndUnwrap(
                                       typeof(Runtime).Assembly.FullName,                                                                    
                                       typeof(Runtime).FullName);



        // start the runtime.  call will marshal into the child runtime appdomain
        runtime.Run<string>(() => "hello!").Dump();
    }
    finally
    {
        // runtime has exited, finish off by unloading the runtime appdomain
        if (childDomain != null && childDomain != AppDomain.CurrentDomain) AppDomain.Unload(childDomain);
    }

}