如何清洁地退出Topshelf

时间:2015-07-08 16:12:53

标签: c# .net topshelf

基于this question的样本处理将自定义参数传递给Topshelf,我现在希望能够干净地退出Topshelf HostFactory。

我有以下代码,它确实有效,但当它“返回”时,控制台会显示一个丑陋的错误,说明Topshelf.HostFactory Error: 0 : An exception occurred creating the host... The service was not properly configured... ServiceBuilderFactory must not be null

我应该使用什么代替return来简单地告诉Topshelf退出而不做任何事情?

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();
});

1 个答案:

答案 0 :(得分:1)

在这种情况下,您不应该在代码中调用.ApplyCommandLine(),这是由Topshelf自动处理的。认识到您此时正在配置主机并且不应该抛出异常非常重要。

命令行值检查的最佳位置是ConstructUsing()方法,您可以在其中验证命令行参数是否存在。如果您的条件不满意,则抛出异常,服务将无法启动。

如果您在其他任何地方执行此操作,请使用install / uninstall / etc的命令行选项。如果没有指定命令行参数,它将无法工作。

相关问题