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

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

I want to pass some custom arguments to the console app when I install and start it as a Windows Service via TopShelf.

When I use:

MyService install start /fooBar: Test 

Console application fails:

[Failure] Command Line An unknown command-line option was found: DEFINE: fooBar = Test

Question:

How can I make my arguments to be recognizable by TopShelf so that I can consume their values?

回答1:

EDIT: This only works when running the .exe, not when running as a service. 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(settings =>     {         settings.ConstructUsing(s => GetInstance());         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(settings =>     {         settings.ConstructUsing(s => GetInstance());         settings.WhenStarted(s => s.Start());         settings.WhenStopped(s => s.Stop());     });      configurator.RunAsLocalService();     configurator.SetServiceName("ServiceName");     configurator.SetDisplayName("DisplayName");     configurator.SetDescription("Description");     configurator.StartAutomatically(); }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!