9
9
using System . ComponentModel ;
10
10
using System . Globalization ;
11
11
using System . IO ;
12
+ using System . Runtime . InteropServices ;
12
13
using System . Linq ;
13
14
using System . Management . Automation . Host ;
14
15
using System . Management . Automation . Remoting ;
15
16
using System . Management . Automation . Runspaces ;
17
+ using System . Reflection ;
16
18
using System . Text ;
17
19
using System . Text . RegularExpressions ;
18
20
using System . Threading ;
@@ -32,6 +34,21 @@ namespace Microsoft.PowerShell.EditorServices
32
34
/// </summary>
33
35
public class PowerShellContext : IDisposable , IHostSupportsInteractiveSession
34
36
{
37
+ private const string DotNetFrameworkDescription = ".NET Framework" ;
38
+
39
+ private static readonly Action < Runspace , ApartmentState > s_runspaceApartmentStateSetter ;
40
+
41
+ static PowerShellContext ( )
42
+ {
43
+ // PowerShell ApartmentState APIs aren't available in PSStandard, so we need to use reflection
44
+ if ( RuntimeInformation . FrameworkDescription . Equals ( DotNetFrameworkDescription ) )
45
+ {
46
+ MethodInfo setterInfo = typeof ( Runspace ) . GetProperty ( "ApartmentState" ) . GetSetMethod ( ) ;
47
+ Delegate setter = Delegate . CreateDelegate ( typeof ( Action < Runspace , ApartmentState > ) , firstArgument : null , method : setterInfo ) ;
48
+ s_runspaceApartmentStateSetter = ( Action < Runspace , ApartmentState > ) setter ;
49
+ }
50
+ }
51
+
35
52
#region Fields
36
53
37
54
private readonly SemaphoreSlim resumeRequestHandle = AsyncUtils . CreateSimpleLockingSemaphore ( ) ;
@@ -175,6 +192,14 @@ public static Runspace CreateRunspace(PSHost psHost)
175
192
}
176
193
177
194
Runspace runspace = RunspaceFactory . CreateRunspace ( psHost , initialSessionState ) ;
195
+
196
+ // Windows PowerShell must be hosted in STA mode
197
+ // This must be set on the runspace *before* it is opened
198
+ if ( RuntimeInformation . FrameworkDescription . Equals ( DotNetFrameworkDescription ) )
199
+ {
200
+ s_runspaceApartmentStateSetter ( runspace , ApartmentState . STA ) ;
201
+ }
202
+
178
203
runspace . ThreadOptions = PSThreadOptions . ReuseThread ;
179
204
runspace . Open ( ) ;
180
205
0 commit comments