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