Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Net Core Worker Service on Windows as well as Linux

Tags:

.net-core

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.

like image 991
Vikrant Avatar asked Jul 12 '20 13:07

Vikrant


People also ask

Is .NET Core compatible with Linux?

NET Core runtime allows you to run applications on Linux that were made with .


1 Answers

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.

like image 127
Jawad Al Shaikh Avatar answered Dec 09 '22 05:12

Jawad Al Shaikh