Hello @Jon ,
Debugging a program running as a service can be tricky - especially when one suspects that the problem is not in one's own code.
What I would try first is to use Event Tracing for Windows (ETW), to see how far the connection process gets before it fails and perhaps compare it with a trace of a successful (interactive) run of the same code.
In this case, the ETW providers that I would include in a "first cut" trace are:
Microsoft-Windows-WLAN-AutoConfig
{637A0F36-DFF5-4B2F-83DD-B106C1C725E2} 0x7FFFFFFF 3 # WLAN Diagnostics Trace
{6DA4DDCA-0901-4BAE-9AD4-7E6030BAB531} 0x7FFFFFFF 4 # WLAN HC Diagnostics Trace
{0C5A3172-2248-44FD-B9A6-8389CB1DC56A} 0x7FFFFFFF 3 # WLAN AutoConfig Trace
{CBE56FBB-D6CB-4C6D-BCA5-1385426707A3} 0x7FFFFFFF 5 # WlanSettings WPP
You could just paste these five lines in a file (say "prov.lst") and the issue the following command to start a trace:
logman start noservice -ets -pf prov.lst -o why.etl
Then reproduce the problem and stop the trace with the command logman stop noservice -ets
You might need to share the trace data here (via OneDrive, Google Drive, etc. links) to extract the most value from the trace data.
Gary