Search code examples
c#windows-servicestopshelf

Get ServiceName/ Instance after calling TopShelf.HostFactory.Run


Is there a way to get the ServiceName and InstanceName given to a TopShelf service after a call to TopShelf.HostFactory.Run()?

One option is to simply pull it directly from the command line args.

But curious if it TopShelf exposes these properties itself.

After digging through source of TopShelf, not seeing a spot/ property that exposes.


Solution

  • You can get service name (and other properties like description and display name) as follows:

            HostFactory.Run(x =>
            {
                x.Service((ServiceConfigurator<MyService> s) =>
                {
    
                    s.ConstructUsing(settings =>
                    {
                        var serviceName = settings.ServiceName;
                        return new MyService();
                    });
                }
             }
    

    Or if your MyService implements ServiceControl

            HostFactory.Run(x =>
            {
                x.Service<MyService>((s) =>
                {
                    var serviceName = s.ServiceName;
    
                    return new MyService();
                });
             }
    /***************************/
    
    class MyService : ServiceControl
    {
        public bool Start(HostControl hostControl) {  }
    
        public bool Stop(HostControl hostControl)  {  }
    }
    

    If you need service name inside MyService just pass it as constructor parameter or property.