1

I have a console .NET application which can be run both from the console and as a windows service (after being registered as such). The process is utilizing the Topshelf .NET library.

In both cases, the entry point is the same - Program.Main, but the command line arguments are different. However, I do not want to base my decision on the command line arguments.

Here is the Topshelf code used by the Main:

var exitCode = HostFactory.Run(configurator =>
{
    configurator.UseNLog();
    configurator.RunAsLocalSystem();
    configurator.SetServiceName(Cfg.ServiceName);
    configurator.SetDescription(serviceDescription);
    configurator.SetDisplayName(serviceDisplayName);
    configurator.EnablePauseAndContinue();

    configurator.Service(factory =>
    {
        var bjeServer = DependencyResolver.Instance.GetInstance<IBJEServer>();
        bjeServer.Initialize();
        return (ServiceControl)bjeServer;
    });
});

if (exitCode != TopshelfExitCode.Ok)
{
    Environment.Exit(1);
}

// This may actually not terminate the process right away. The reason - Quartz may still be waiting for jobs to finish, which may take hours.
return 0;

I am OK if the solution is Topshelf specific. A general one is welcome as well.

mark
  • 59,016
  • 79
  • 296
  • 580
  • 2
    Just out of curiosity, *why* wouldn't you base it off the command line arguments if thats a fool-proof way to check if its in console or service mode? – BradleyDotNET Jan 14 '15 at 01:26
  • Why do you care if you're running as a service? What do you need to accomplish? – John Saunders Jan 14 '15 at 01:38
  • @BradleyDotNET - I did not say it is a fool proof way. The command line arguments are pretty straightforward - "-servicename aaa -displayname bbb", nothing fancy. The user could easily provide them on the command line, which by the way makes sense for a console mode as well. – mark Jan 14 '15 at 02:02
  • @JohnSaunders - there are reasons. Curiosity is one of them, not the most important, but still legitimate. – mark Jan 14 '15 at 02:03
  • 1
    I didn't say there were no reasons - I just asked what those reasons _were_. There might be another way to accomplish those purposes. – John Saunders Jan 14 '15 at 02:15

0 Answers0