Development Windows

Cannot start windows service when using Microsoft.Extensions.Hosting.WindowsServices

I tried to follow the recommendations here for creating a Windows service using Microsoft.Extensions.Hosting.WindowsServices. So far so good, everything works fine, my background service’s ExecuteAsync gets called and the log says that everything is OK. Starting the application as a console application works fine, too, I can start it, do whatever I need to do, then stop it.

However, I try then to install the Windows service using:

sc create myservice binPath= "\"<path-to-the-exe-file>\" service" start= auto DisplayName= "My Service"

I get [SC] CreateService SUCCESS. But when I try to start the service manually, it tells me that it did not respond in timely manner. Again, the log is fine, no errors. The Event Viewer tells me nothing more about what it can go wrong and I don’t have any clue what can I do next to find the cause of the problem.

This is the class I use for the background service.

public class BackgroundWorker : BackgroundService
    private readonly IAppContext appContext;
    private CancellationTokenRegistration stopRegistration;

    public BackgroundWorker(ILogger<BackgroundWorker> logger, IAppContext appContext)
        this.Logger = logger;
        this.appContext = appContext;

    public ILogger<BackgroundWorker> Logger { get; }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
        this.Logger.Info("Background worker started.");

        this.stopRegistration = stoppingToken.Register(() =>
            this.Logger.Info("Background worker stopping...");
            this.Logger.Info("Background worker stopped.");

        return Task.CompletedTask;


Here is an approximate code I used to configure the host:

            var containerBuilder = new ContainerBuilder();
            IContainer container = null; 

            var hostBuilder = Host.CreateDefaultBuilder(appArgs);
                .UseServiceProviderFactory(new CustomAutofacServiceProviderFactory(() => container))
                .ConfigureServices(services =>
                        container = containerBuilder.Build();

Leave a Reply

Your email address will not be published. Required fields are marked *