4

This is not a duplicate of this post, as I already attempted the recommended solutions in there.

I've been trying to start my C#/.netCore 3.0/Kestrel as a service.

After struggling to get my app to start as a service, I followed these instructions to create a new exe, with the same result.

After publishing, and adding the service, and trying to start the service from either cmd, powershell, or the service interface, I am prompted with the following message :

Windows could not start the SomeWorker service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion.

On investigating the system event log, I only see a generic :

The myWorker service failed to start due to the following error: The service did not respond to the start or control request in a timely fashion.

When I run the exe/console, it starts up fine without any problems.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging(
                options => options.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Information))
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>()
                    .Configure<EventLogSettings>(config =>
                    {
                        config.LogName = "Sample Service";
                        config.SourceName = "Sample Service Source";
                    });
            }).UseWindowsService();
}


public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;

    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}
4
  • Basically, the windows service OnStart event should complete within 30seconds. I am not sure it still holds true in the .NET Core world. Are you doing some heavy work during the startup? Commented Jan 10, 2020 at 10:09
  • @Thangadurai. Not at all. This was my first instinct as well. Everything I have in the solution, is what you see in the code above. I've even tried increasing the timeout via regedit, but still receive the same result.
    – WynDiesel
    Commented Jan 10, 2020 at 10:13
  • Have you tried adding a System.Diagnostic.Debugger.Break call in somewhere to see if you can get a debug session going when it starts?
    – Moo-Juice
    Commented Jan 10, 2020 at 10:41
  • I tried the same example that you have posted. I haven't changed anything, but it works for me and I am able to see the log messages in the Event Viewer. Can you check on which user account or service account your service is created/running? Commented Jan 10, 2020 at 11:24

4 Answers 4

6

The issue was that Visual Studio was not set to deploy the service as self-contained.

After setting this in the project's properties, everything worked fine.

8
  • 2
    how did you make the service as self-contained?
    – Franva
    Commented Aug 9, 2020 at 3:34
  • @franva I can't recall the exact way now, and I don't have a visual studio close by to check, but when you right click, publish, there should be an option to setup a self contained .net core publish
    – WynDiesel
    Commented Aug 10, 2020 at 4:20
  • 1
    @Franva: use Folder and then click on the edit button to configure the profile.
    – Sebastian
    Commented Aug 10, 2020 at 8:23
  • 1
    @WynDiesel: I found this option but it doesn't solve the problem. I still get the error 1053. I use VS2019 but I also tried to publish via dotnet.exe in the console.
    – Sebastian
    Commented Aug 10, 2020 at 8:25
  • 4
    hi @Sebastian I solved my problem. I missed 2 things. 1. .UseWindowsService(), 2. install a nuget package. I found both on the Microsoft doc website.
    – Franva
    Commented Aug 10, 2020 at 12:56
6

There are some points to verify.

  1. Intall Microsoft.Extensions.Hosting.WindowsServices and use it in your project. You can use some log package like Serilog, but it is optional.

enter image description here

  1. Configure the publish with your options. Important to check ReadyToRun and Self-contained.

enter image description here

1
  • #1 was an issue for me, thank you.
    – Greg Gum
    Commented May 24, 2023 at 21:34
5

Not sure if this will help, I had the same problem. It came down to this in my CreateHostBuilder method:

    host.ConfigureAppConfiguration(
        (hostContext, config) =>
        {
            config.SetBasePath(Directory.GetCurrentDirectory());
            config.AddJsonFile("appsettings.json", false, true);
        }
    );

It turns out the above is no longer necessary as calling CreateDefaultBuilder will set the base path and add appsettings.json. Here is what my CreateHostBuilder now looks like (and it works fine):

        var host = Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureLogging(loggingBuilder =>
            {
                var configuration = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json")
                    .Build();
                var logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(configuration)
                    .CreateLogger();
                loggingBuilder.AddSerilog(logger, dispose: true);
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<SrtLmcoMaximoSyncWorker>();
            });
        return host;
3

This is the issue that I faced:

I wanted a .net core 6 Windows Service. So I create a Project using the Background Worker template which appears to run fine in Visual Studio. However, when the project was published and run as a service on Windows Server, the service would fail to start. Checking the event log showed no exceptions.

This issue is that a Background worker project will not run as-is as a Windows Service. It's close, but you must add this code to ensure it actually works with the Windows Service Manager:

IHost host = Host.CreateDefaultBuilder(args)
 .UseWindowsService(options =>
 {
     options.ServiceName = "Your Service Name";
 })

Also, ensure you add Microsoft.Extensions.Hosting.WindowsServices lib to your project.

Full Windows Service Walkthrough project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.