I'm attempting to create an open source library that spawn a new AppDomain
and runs a PowerShell
script in it. I have a static method that takes the name of the powershell file and the name of the AppDomain
. The method executes successfully when called from a C# console app, but not PowerShell
.
I know the dll is being loaded in the second app domain because of this entry in the fusionlog.
The class declaraton and constructor looks like this.
public class AppDomainPoshRunner : MarshalByRefObject{
public AppDomainPoshRunner (){
Console.WriteLine("Made it here.");
}
}
That message in the constructor gets output when I call CreateInstanceFromAndUnwrap whether I run the dll from a C# console app or from the PowerShell app.
The failure occurs when I cast the value returned by CreateInstanceFromAndUnwrap
to AppDomainPoshRunner in the static method below.
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);
}
}
When running that in PowerShell I get an InvalidCastExcception
with the message Unable to cast transparent proxy to type JustAProgrammer.ADPR.AppDomainPoshRunner
.
What am I doing wrong?