• Stars
    star
    451
  • Rank 96,968 (Top 2 %)
  • Language
    C#
  • License
    MIT License
  • Created about 8 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Helper classes to set up and run as windows services directly on .net core. A ServiceBase alternative.

.NET Standard-based Windows Service support for .NET

This repo contains a library for running a .NET Core application as Windows service without the need for a wrapper assembly or the full (desktop) .NET Framework. It is built using P/Invoke calls into native Windows assemblies.

Usage scenarios include:

  • Running on Windows Nano Server (no full framework but can run Windows services)
  • Shipping a modern service application using the latest .NET Core version to systems where you cannot upgrade to new versions of .NET, but you want to use new framework features.
  • Build truly portable applications that can for example run as service on Windows and as daemon on Linux, just using runtime checks / switches

How to use the example application

Prerequisites:

  • .NET Core SDK 2.0.3 or higher (.csproj based tooling)
  • Windows machine
  • Elevated command prompt: Run cmd as administrator.
> cd samples\TestService
> dotnet restore
> dotnet run --register-service --urls http://*:5080
...
Successfully registered and started service "Demo .NET Core Service" ("Demo ASP.NET Core Service running on .NET Core")

Open http://localhost:5080 in a browser. You should see Hello world.

The "Services" administrative tool should show the service: running service running service

> dotnet run --unregister-service
...
Successfully unregistered service "Demo .NET Core Service" ("Demo ASP.NET Core Service running on .NET Core")

The service may show up as disabled for some time until all tools accessing the Windows services APIs have been closed. See this Stack Overflow question.

API

Add a NuGet package reference to DasMulli.Win32.ServiceUtils.

Write a Windows service using:

using DasMulli.Win32.ServiceUtils;

class Program
{
    public static void Main(string[] args)
    {
        var myService = new MyService();
        var serviceHost = new Win32ServiceHost(myService);
        serviceHost.Run();
    }
}

class MyService : IWin32Service
{
    public string ServiceName => "Test Service";

    public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
    {
        // Start coolness and return
    }

    public void Stop()
    {
        // shut it down again
    }
}

You can then register your service via sc.exe (run cmd / powershell as administrator!):

sc.exe create MyService DisplayName= "My Service" binpath= "C:\Program Files\dotnet\dotnet.exe C:\path\to\MyService.dll --run-as-service"

Now go to Services or Task Manager and start your service.

sc will install your service as SYSTEM user which has way to many access rights to run things like web apps. See its reference for more options.

If you want to get rid of it again, use:

sc.exe delete MyService

You can also create a service that registers itself like the example provided by taking a look at the sample source.

Also take a look at the ASP.NET Core MVC sample which has additional logic to set the correct working directory. When running it in development and not from the published output, be sure to pass --preserve-working-directory to it when registering so that it will run from the project directory (e.g. run dotnet run --register-service --preserve-working-directory from and administrative command prompt).

Pause & Continue support

To create a service that supports being paused and later continued or stopped, implement IPausableWin32Service which extends IWin32Service by Pause() and Continue() methods you can use to implement your pause & continue logic.

Limitations

  • No custom exceptions / error codes. Everything will throw a Win32Exception if something goes wrong (Its message should be interpretable on Windows).
  • All exceptions thrown by the service implementation will cause the service host to report exit code -1 / 0xffffffff to the service control manager.
  • Currently, no direct support for services supporting commands such as power event and system shutdown
    • However, consumers can now use IWin32ServiceStateMachine to implement custom behavior. Copy SimpleServiceStateMachine as a starting point to implement extended services.

More Repositories

1

data-builder-generator

Code generator to easily create data builder patterns for your model classes
C#
117
star
2

LocalNupkgExample

Example to demonstrate local nuget packages
C#
21
star
3

SimpleGitVersion

Simple Git prerelease versioning integrated into SDK-based msbuild projects
17
star
4

rider-msbuild-webinar-2020

Sample repository for JetBrains Rider Webinar on MSBuild from December 2020
C#
17
star
5

nuget-include-p2p-example

Example of a NuGet package including its ProjectReference projects
C#
14
star
6

ConfigSampleWebApp

Sample showing how to use appsettings.json for .NET 4.7.1 configuration builders
C#
10
star
7

AdvancedMSBuildDemos

Advanced MSBuild demos
TypeScript
8
star
8

AssemblyInfoGenerationSdk

Extracts .NET SDK AssemblyInfo.cs generation into an SDK for use in legacy project types
C#
8
star
9

hungarian-algorithm

Hungarian method a.k.a. Kuhnโ€“Munkres Algorithm for .NET
C#
7
star
10

hw-intrinsics-samples

Samples for hardware intrinsic comparisons
C#
3
star
11

HelloMSBuildDemos

MSBuild Demos
3
star
12

k8s-demos-2022

TypeScript
3
star
13

k8s-demos-2020

Kubernetes Demos
TypeScript
2
star
14

swetugg-2024-msbuild-demos

Demo code used during the 2024 Swetugg session on MSBuild
C#
2
star
15

CSProjDemos

MSBuild .csproj based demos
C#
2
star
16

dotnext-2020-samples

Samples for DotNext Moscow 2020
C#
2
star
17

exploring-source-generators

C#
2
star
18

so-config-example

Sample for SO question https://stackoverflow.com/questions/45559570/appsettings-json-in-netcore-console-application
C#
2
star
19

alerter-static-app-demo

Azure Static Web App Demo using Blazor WebAssembly and Azure Functions with Microsoft Graph
C#
1
star
20

dasmulli.github.io

http://dasmulli.github.io
HTML
1
star
21

msbuild-metadata-filter-example

Example project that shows how custom metadata and regular expressions can be used in MSBuild to filter items
C#
1
star
22

DevOpsTraining-2019-02

Azure DevOps training material
C#
1
star
23

GlobalCliToolsExample

Example for global CLI tools
C#
1
star
24

net-stammtisch-10

Samples for .NET Stammtisch #10
C#
1
star
25

dotnet-tuning-demos

Demos for .NET optimization and deployment options
C#
1
star