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

后端 未结 1 491
天涯浪人
天涯浪人 2020-12-16 11:04

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          


        
相关标签:
1条回答
  • 2020-12-16 11:31

    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();
    });
    
    0 讨论(0)
提交回复
热议问题