Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c# - 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...