我正在尝试创建一个开源库,该库会生成一个新库AppDomain
并在其中运行一个PowerShell
脚本。我有一个静态方法,它采用 powershell 文件的名称和AppDomain
. 从 C# 控制台应用程序调用该方法时成功执行,但不是PowerShell
.
由于fusionlog 中的此条目,我知道 dll 正在第二个应用程序域中加载。
类声明和构造函数看起来像这样。
public class AppDomainPoshRunner : MarshalByRefObject{
public AppDomainPoshRunner (){
Console.WriteLine("Made it here.");
}
}
无论我是从 C# 控制台应用程序还是从 PowerShell 应用程序运行 dll,当我调用CreateInstanceFromAndUnwrap时,构造函数中的该消息都会得到输出。
当我在下面的静态方法中将返回的值CreateInstanceFromAndUnwrap
转换为AppDomainPoshRunner时会发生故障。
public static string[] RunScriptInAppDomain(string fileName, string appDomainName = "Unamed")
{
var assembly = Assembly.GetExecutingAssembly();
var setupInfo = new AppDomainSetup
{
ApplicationName = appDomainName,
// TODO: Perhaps we should setup an even handler to reload the AppDomain similar to ASP.NET in IIS.
ShadowCopyFiles = "true"
};
var appDomain = AppDomain.CreateDomain(string.Format("AppDomainPoshRunner-{0}", appDomainName), null, setupInfo);
try {
var runner = appDomain.CreateInstanceFromAndUnwrap(assembly.Location, typeof(AppDomainPoshRunner).FullName);
if (RemotingServices.IsTransparentProxy(runner))
Console.WriteLine("The unwrapped object is a proxy.");
else
Console.WriteLine("The unwrapped object is not a proxy!");
Console.WriteLine("The unwrapped project is a {0}", runner.GetType().FullName);
/* This is where the error happens */
return ((AppDomainPoshRunner)runner).RunScript(fileName);
}
finally
{
AppDomain.Unload(appDomain);
}
}
在 PowerShell 中运行它时,我收到InvalidCastExcception
消息Unable to cast transparent proxy to type JustAProgrammer.ADPR.AppDomainPoshRunner
。
我究竟做错了什么?