1

I have an application running on .NET Core 2.1.7.
This will be installed on my customers' machines.
I want to run this as a Windows Service.

How can I do that?
And what would be the best way?

Self-hosting:

public class Program
{
    public static void Main(string[] args)
    {
        var isService = !(Debugger.IsAttached || args.Contains("--console"));
        var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());

        if (isService)
        {
            var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);
            builder.UseContentRoot(pathToContentRoot);
        }

        var host = builder.Build();

        if (isService)
        {
            host.RunAsService();
        }
        else
        {
            host.Run();
        }
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75

1 Answers1

0

Since you do: var isService = !(Debugger.IsAttached || args.Contains("--console")); once you publish your application will always try to run as a service with host.RunAsService();. If you will try to run it by calling the .exe program it will give you an error.

In order to create a windows service you just have to run the following command in a command prompt with adminitrator privileges:

sc create ServiceName binPath= "c:\pathtoexe\file.exe"

Also make sure to leave a whitespace after "binPath= " or the command will not be considered.

LMio
  • 126
  • 1
  • 9