.NET Core Workers as Windows Services

Glenn Condron [MSFT]

In .NET Core 3.0 we are introducing a new type of application template called Worker Service. This template is intended to give you a starting point for writing long running services in .NET Core. In this walkthrough we will create a worker and run it as a Windows Service.

Create a worker

Preview Note: In our preview releases the worker template is in the same menu as the Web templates. This will change in a future release. We intend to place the Worker Service template directly inside the create new project wizard.

Create a Worker in Visual Studio

image

image

image

Create a Worker on the command line

Run dotnet new worker

image

Run as a Windows Service

In order to run as a Windows Service we need our worker to listen for start and stop signals from ServiceBase the .NET type that exposes the Windows Service systems to .NET applications. To do this we want to:

Add the Microsoft.Extensions.Hosting.WindowsServices NuGet package

image

Add the UseServiceBaseLifetime call to the HostBuilder in our Program.cs

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseServiceBaseLifetime()
            .ConfigureServices(services =>
            {
                services.AddHostedService<Worker>();
            });
}

This method does a couple of things. First, it checks whether or not the application is actually running as a Windows Service, if it isn’t then it noops which makes this method safe to be called when running locally or when running as a Windows Service. You don’t need to add guard clauses to it and can just run the app normally when not installed as a Windows Service.

Secondly, it configures your host to use a ServiceBaseLifetime. ServiceBaseLifetime works with ServiceBase to help control the lifetime of your app when run as a Windows Service. This overrides the default ConsoleLifetime that handles signals like CTL+C.

Install the Worker

Once we have our worker using the ServiceBaseLifetime we then need to install it:

First, lets publish the application. We will install the Windows Service in-place, meaning the exe will be locked whenever the service is running. The publish step is a nice way to make sure all the files I need to run the service are in one place and ready to be installed.

dotnet publish -o c:\code\workerpub

Then we can use the sc utility in an admin command prompt

sc create workertest binPath=c:\code\workerpub\WorkerTest.exe

For example:

image

Security note: This command has the service run as local system, which isn’t something you will generally want to do. Instead you should create a service account and run the windows service as that account. We will not talk about that here, but there is some documentation on the ASP.NET docs talking about it here: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-2.2

Logging

The logging system has an Event Log provider that can send log message directly to the Windows Event Log. To log to the event log you can add the Microsoft.Extensions.Logging.EventLog package and then modify your Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(loggerFactory => loggerFactory.AddEventLog())
        .ConfigureServices(services =>
        {
            services.AddHostedService<Worker>();
        });

Future Work

In upcoming previews we plan to improve the experience of using Workers with Windows Services by:

  1. Rename UseWindowsServiceBaseLifetime to UseWindowsService
  2. Add automatic and improved integration with the Event Log when running as a Windows Service.

Conclusion

We hope you try out this new template and want you to let us know how it goes, you can file any bugs or suggestions here.

33 comments

Discussion is closed. Login to edit/delete existing comments.

  • Naveed Butt 0

    Since this blog post was pre VS 2019 release, I assume that every thing worked well on VS 2019 RC. Now I have installed VS 2019 Enterprise, why do I need to install RC as well, just to play around with .Net Core 3.0 features?
    Maybe this question is not suitable for this blog post, but I couldn’t find a suitable place for the question… 

  • King David Consulting LLC 0

    I just updated to <a href="https://github.com/kdcllc/CronScheduler.AspNetCore/" rel="nofollow">https://github.com/kdcllc/CronScheduler.AspNetCore/</a> to support Worker cron scheduled jobs to be executed inside the console.

  • Daniel Carvalho Liedke 0

    Hello, using preview6, after creating a new worker project without any code change, when I try to start the service it times out. How can I get this fixed? Thanks,
    Daniel 

  • Erik Parso 0

    Is there a way desktop client can communicate with service ? 

  • Michael T. DePouw Spottedmahn 0

    I tried creating a new worker service project but it doesn’t build 😢
    Developer Community Issue

  • Tom Burgin 0

    Hey Glenn,

    Could we get an updated guide now that 3.0 is released? I notice, for example, UseServiceBaseLifetime has now been replaced by UseWindowsService. I’m thinking there are probably some more changes required but I’m not sure!

    Cheers,
    Tom

  • Ballantyne, David 0

    Thanks for the clear and concise example.

    Had to research and add the following additions to get this to work:

    1) Change “.UseServiceBaseLifetime()” to “.UseWindowsService()”

    2) To get logging to show up in the event logger:
    a) add the two following “Using…” commands to the top of Program.cs:
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Logging.EventLog;

    b) Per this link, add:

    ,
    "EventLog": {
    "LogLevel": {
    "Default": "Information",
    "Microsoft.Hosting.Lifetime": "Information"
    }
    }

    … to your appsettings.json after the orig “LogLevel” section (yes, there will then be two LogLevel sections but at different nodes, and don’t miss the little comma).

  • John Lonewolf 0

    you should change your sc command to this:
    sc create binpath=[SPACE][absolute path to exe] start=[SPACE]auto
    There need to be a space between binpath= and the path, else it won’t be able to find the exe of the service, and between start= and auto (to make it auto start with system).

    One question I have.. I’ve managed to create a windows service based on a grpc service+worker and with the Microsoft.Extensions.Hosting.WindowsServices nuget package, and using sc create, I can see that it’s running as windows service.

    Now, in the Worker class, I override the startAsync and stopAsync, and I noticed that when system starts up, the startAsync is called, but when system shuts down, the stopAsync is not called. I tried using IHostingApplicationLifetime in the Startup to detect application start and stop and I noticed the same thing too. Application start is called, but application stop is not called. Is this a bug in the windows service nuget package or BackgroundService? Previously I’ve used IApplicationLifetime interface in asp.net core’s web api in Startup and hosting it in IIS, and I was able to detect the system start and stop.

    Could you please advice me? I’m using VS2019 Pro with .net core 3.0.100.

  • Design Engineer 0

    I think the core 3.1 Template is broken at the moment, looks like the web default template

  • Marco Leite 0

    Is It possible to implement Integration and System tests on a Service Worker (.NET Core 3.1)?
    If so, how can we deal with injected properties in Integration tests?
    For System tests, how can we deploy and verify results?

    Any suggestions, ideas or examples?

    Thanks in advance,
    M.

Feedback usabilla icon