Arkin , I'm not too sure if this the "good way". But I did some experimenting related to this (in PowerShell), maybe you can use it as inspiration:
Create a remote session to localhost - means your session runs locally but will be accessible from multiple consoles/instances:
# From Console 1:
# Create new remote session to local host with idle timeout of 15 minutes
$session = New-PSSession -ComputerName . -SessionOption (New-PSSessionOption -IdleTimeout 900000)
# Get session InstanceId and save it for reconnecting later
$guid = $session.InstanceId
[GUID]::Parse($guid)
Establish an Exchange Online session inside the session you just created:
# Establish credentials variable in new remote session:
Invoke-Command -Session $session -ScriptBlock {$cred = Get-Credential}
# Establish EXO session in new remote session:
Invoke-Command -Session $session -ScriptBlock {$EXOSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true -Credential $cred -Authentication Basic -AllowRedirection}
(replace EXO connection with your preferred style/format)
You now have a $EXOSession inside your $Session and both will exist (in connected state) until the timeout expires. The TTL get's refreshed every time you use it.
# Get mailbox from EXO using EXO session inside remote session (which is actually local)
Invoke-Command -Session $session -ScriptBlock {Invoke-Command -Session $EXOsession {get-mailbox ole.roemer}}
# Disconnect from remote session:
Disconnect-PSSession $session
(this doesn't end the session, it stays fresh and dormant)
Open up another PowerShell console to simulate another script running:
# From Console 2:
# View existing sessions:
Get-PSSession -ComputerName localhost | fl
Get a hold on the session created in Console 1:
# Get reference to the session from before:
$session = Get-PSSession -ComputerName localhost -InstanceId ([GUID]"enter-guid-from-before")
# Connect to the session:
Connect-PSSession $session
# get mailbox using the EXO session in the remote session:
Invoke-Command -Session $session -ScriptBlock {Invoke-Command -Session $EXOsession {get-mailbox ole.roemer}}
Disconnect-PSSession $session
It's not pretty. At all. But it saves your application the trouble of reconnecting. Lot's of reconnects might get throttled.
Hope you can use this as inspiration
/ Morten
Easy Office 365 administration: https://easy365manager.com