Vikrant
Vikrant

Reputation: 283

Net Core Worker Service on Windows as well as Linux

The context is .Net Core Worker Service. I want to run it as a Windows Service when deployed on a Windows OS and as a daemon when deployed on a Linux OS. But I want to keep only one binary for deployment on both Windows and Linux.

This article (and many other) pipe either UseWindowsService or UseSystemd, which means that in order for this worker service to run on Winodws and Linux, has to have two different binaries.

As I am new to DotNet Core, I want to learn/know whether or not it can conditionally pipe the UseWindowsService/UseSystemd based on the OS - keeping only one binary.

Upvotes: 9

Views: 4998

Answers (1)

Jawad Al Shaikh
Jawad Al Shaikh

Reputation: 2735

As @Lex Li commented, Single binary for Cross-Platform isn't supported in .Net Core, actually I never came across any native binary (hence HTML, JS, JAVA ".jar, .ear, .war" doesn't count) capable of that

Below snippet is the minimal code to create daemon and windows service:

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

The UseSystemd method will noop when not running as a daemon so you can still run and debug your app normally or use it in production both with and without systemd.

the .UseWindowsService() and .UseSystemd() are NOOP so they will only work in their respective environments, So on Windows .UseSystemd() is No-Operation (just do nothing) and in Linux .UseWindowsService() is No-Operation (just do nothing).

Remark: Build automation is the common approach used by popular software to build cross-platform binaries.

Upvotes: 14

Related Questions