如何使用TopShelf无法识别的CommandLine参数?

pen*_*ake 21 .net c# windows-services topshelf

我想在安装时将一些自定义参数传递给控制台应用程序,并通过TopShelf将其作为Windows服务启动.

我用的时候:

MyService install start /fooBar: Test
Run Code Online (Sandbox Code Playgroud)

控制台应用失败:

[Failure]命令行找到了一个未知的命令行选项:DEFINE:fooBar = Test

题:

如何让我的参数被TopShelf识别,以便我可以消耗它们的值?

Lau*_*nce 32

编辑:这仅在运行.exe时有效,而不是在作为服务运行时.作为替代方案,您可以将选项添加为配置值并在启动时读取它(这可能是更好的做法):

using System.Configuration;

// snip

string foobar = null;

HostFactory.Run(configurator =>
{
    foobar = ConfigurationManager.AppSettings["foobar"];

    // do something with fooBar

    configurator.Service<ServiceClass>(settings =>
    {
        settings.ConstructUsing(s => GetInstance<ServiceClass>());
        settings.WhenStarted(s => s.Start());
        settings.WhenStopped(s => s.Stop());
    });

    configurator.RunAsLocalService();
    configurator.SetServiceName("ServiceName");
    configurator.SetDisplayName("DisplayName");
    configurator.SetDescription("Description");
    configurator.StartAutomatically();
});
Run Code Online (Sandbox Code Playgroud)

根据文档,您需要在此模式中指定命令:

-foobar:Test
Run Code Online (Sandbox Code Playgroud)

您还需要在服务配置中添加定义:

string fooBar = null;

HostFactory.Run(configurator =>
{
    configurator.AddCommandLineDefinition("fooBar", f=> { fooBar = f; });
    configurator.ApplyCommandLine();

    // do something with fooBar

    configurator.Service<ServiceClass>(settings =>
    {
        settings.ConstructUsing(s => GetInstance<ServiceClass>());
        settings.WhenStarted(s => s.Start());
        settings.WhenStopped(s => s.Stop());
    });

    configurator.RunAsLocalService();
    configurator.SetServiceName("ServiceName");
    configurator.SetDisplayName("DisplayName");
    configurator.SetDescription("Description");
    configurator.StartAutomatically();
});
Run Code Online (Sandbox Code Playgroud)

  • 在AddCommandLineDefinition()之后和//执行某些操作之前,您需要添加以下行:configurator.ApplyCommandLine(); (3认同)
  • “*由于您经常在 lambda 表达式中传递 lambda 表达式,因此很难弄清楚如何正确设置某些内容*” - 通过这种推理可能会争论“由于您经常在调用其他方法的方法中传递参数,因此很难弄清楚如何正确设置正确设置一些东西”。嵌套 lambda 并不比常规方法更难处理。我猜你只是不“熟悉”它们。这不是一个复杂性问题,而是一个教育和熟悉度问题。 (2认同)