Search code examples
c#topshelf

Topshelf and .net core under linux


I have a simple application that starts as a service using topshelf and it looks simple:

 HostFactory.Run(x =>
 {
    x.Service<RequestService>();
    x.RunAsLocalSystem();
 });

Well it works, but under windows. When I tried this under Linux I am getting:

Topshelf.Runtime.Windows.WindowsHostEnvironment Error: 0 : Unable to get parent process (ignored), System.DllNotFoundException: Unable to load shared library 'kernel32.dll' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libkernel32.dll: cannot open shared object file: No such file or directory

Has someone came across this problem? I tried to google it but someone said it works other that it is tool only for windows.

Or maybe there is some other service hoisting framework for .net core?


Solution

  • Topshelf is not advertised as cross-platform and so it does not (or did not at the time of writing) official support .Net Core on non-Windows environments, even if it can run in them (at least at the time of writing, see below).

    The solution is to change the environment builder when running on non-Windows hosts.

    Here is an example from my project. When creating the service, pick the env builder at runtime based on the host OS.

    HostFactory.Run(c =>
    {
      // Change Topshelf's environment builder on non-Windows hosts:
      if (
        RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ||
        RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
      )
      {
        c.UseEnvironmentBuilder(
          target => new DotNetCoreEnvironmentBuilder(target)
        );
      }
    
      c.SetServiceName("SelloutReportingService");
      c.SetDisplayName("Sellout Reporting Service");
      c.SetDescription(
        "A reporting service that does something...");
      c.StartAutomatically();
      c.RunAsNetworkService();
      c.EnableServiceRecovery(
        a => a.RestartService(TimeSpan.FromSeconds(60))
      );
      c.StartAutomatically();
      c.Service<SelloutReportingService>();
    });