简体   繁体   English

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

[英]How can I use CommandLine Arguments that is not recognized by TopShelf?

I want to pass some custom arguments to the console app when I install and start it as a Windows Service via TopShelf. 我想在安装时将一些自定义参数传递给控制台应用程序,并通过TopShelf将其作为Windows服务启动。

When I use: 我用的时候:

MyService install start /fooBar: Test

Console application fails: 控制台应用失败:

[Failure] Command Line An unknown command-line option was found: DEFINE: fooBar = Test [Failure]命令行找到了一个未知的命令行选项:DEFINE:fooBar = Test

Question: 题:

How can I make my arguments to be recognizable by TopShelf so that I can consume their values? 如何让我的参数被TopShelf识别,以便我可以消耗它们的值?

EDIT: This only works when running the .exe, not when running as a service. 编辑:这仅在运行.exe时有效,而不是在作为服务运行时。 As an alternative you could add the option as a configuration value and read it at start-up (which is probably better practice anyway): 作为替代方案,您可以将选项添加为配置值并在启动时读取它(这可能是更好的做法):

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

According to the documentation you need to specify the commands in this pattern: 根据文档,您需要在此模式中指定命令:

-foobar:Test

You also need to add the definition in your service configuration: 您还需要在服务配置中添加定义:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM