Search code examples
topshelf

TopShelf ConstructUsing vs WhenStarted


I wanted to ask what operations should be pleaced in ConstructUsing and what in WhenStarted. In fact things which normally are placed in contructor like configuration read, initialization in case of service should be placed in WhenStarted IMO in order to refresh all things during service restart, so what is left for ConstructUsing? just newing up the class and that's all? But in that case why not newing up in WhenStarted as well?

Thanks in advance


Solution

  • ConstructUsing defines how to create your service, which can indeed just be a new(), or alternatively another way of obtaining the service:

    For example, using IoC:

    // Release in WhenStopped()
    sc.ConstructUsing(() => container.Resolve<IMyService>());
    

    Another option is to use an existing instance of the service:

    sc.ConstructUsing(() => serviceInstance);
    

    WhenStarted, on the other hand, defines what actions to take when the instance of the service starts, and so requires an instance to configure: you wouldn't be able to create the service here:

    sc.WhenStarted(service => service.Start());