How to detect if Topshelf is running in console mode
You can use Environment.UserInteractive
. Technically this won't work in 100% of the cases as it is possible to run a service in user-interactive mode, but this is a fringe case.
It's sort of a hack, but you can try to cast the HostControl
interface to ConsoleRunHost
, and if it's that type, you're running as a console application.
It's not ideal, sure, but surely you can hide this in an extension method to make it less ugly.
public static bool IsRunningAsConsole(this HostControl control)
{
return control is ConsoleRunHost;
}
And you then get access to the HostControl by passing it in through the call to WhenStarted() in your service configuration.
s.WhenStarted((tc, hostControl) => tc.Start(hostControl));