4

Based off the sample at this question which deals with passing custom parameters to Topshelf, I now want to be able to cleanly exit out of the Topshelf HostFactory.

I have the following code, and it does work, but when it "returns", the console displays an ugly error stating Topshelf.HostFactory Error: 0 : An exception occurred creating the host... The service was not properly configured... ServiceBuilderFactory must not be null

What should I uses instead of return to simply tell Topshelf to exit and not do anything?

string foo = null;
HostFactory.Run(x =>
{
    x.AddCommandLineDefinition("foo", f => { foo = f; });
    x.ApplyCommandLine();
    if (!string.IsNullOrEmpty(foo))
    {
        Console.WriteLine("A value for Foo was received... exiting.");
        return;
    }

    x.Service<MyService>(s =>
    {
        s.ConstructUsing(() => new MyService());
        s.WhenStarted(z => z.Start());
        s.WhenStopped(z => z.Stop());
    });
    x.StartAutomatically();
});
Community
  • 1
  • 1
bigmac
  • 2,553
  • 6
  • 38
  • 61
  • @stuartd the rationale "if you deploy it as a service, then you won't notice those errors" is kind of silly, and not super constructive. -- Not to mention, it probably wont even run as a service, since this error is clearly indicative of a deeper issue. – BrainSlugs83 Feb 01 '17 at 00:58
  • @BrainSlugs83 fair enough – stuartd Feb 01 '17 at 10:25

1 Answers1

2

In this case, you should not be calling .ApplyCommandLine() in your code, that's automatically handled by Topshelf. And it's important to recognize that you're configuring the host at this point, and should not be throwing an exception.

The best place for your command-line value check is in the ConstructUsing() method, where you can verify the command-line arguments are present. If your conditions are not satisfied, throw an exception and the service will fail to start.

If you do it anywhere else, the command-line options for install/uninstall/etc. will not work without that command-line parameter specified.

Chris Patterson
  • 28,659
  • 3
  • 47
  • 59