.NET Core 3.1 Console App as a Windows Service

Viewed 10926

I currently have a pretty big console app running with ASP.NET Core 3.1. I have been tasked with now making this work on one of our servers as a Window Service. I have everything ready to make it run as a service on the server itself, however, the one thing I am stuck on at the moment is how to actually change it in code to make it run as a service without breaking it.

I have found a couple of tutorials like this that do explain how to run a console app as a service, however, all of them that I have found start from a fresh project. My issue is that my current project has already been written. The main problem that I am asking for help with is how would I go about making my project work as a windows service while also keeping the functionality that is currently in a startup.cs. For context, here is my current startup.cs and program.cs:

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSignalR();
        services.AddTransient<SharePointUploader>();
        services.AddTransient<FileUploadService>();
        services.AddSingleton<UploaderHub>();
        //services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
        services.AddAuthorization();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHttpsRedirection();
        }

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<UploaderHub>("/uploadHub");
        });
    }
}

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception exception)
        {
            //NLog: catch setup errors
            logger.Error(exception, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Trace);
            })
            .UseNLog();
}

I don't really understand how this is supposed to work when run as a windows service (based on tutorials like linked above). Any help would be greatly appreciated.

3 Answers

I forgot about answering this question as I solved it a few hours later after I asked it, but you can just add ".UseWindowsService()" to the Host.CreateDefaultBuilder(args) line. eg:

 public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()                     //<==== THIS LINE
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Trace);
            })
            .UseNLog();

Use IWebHostBuilder instead of IHostBuilder:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            // Configure the app here.
        })
        .UseNLog()
        .UseUrls("http://localhost:5001/;" +
                    "https://localhost:5002/;")
        .UseStartup<Startup>();

You also need the following packages:

Microsoft.AspNetCore.Hosting;
Microsoft.AspNetCore.Hosting.WindowsServices;

Modify your main function:

bool isService = !(Debugger.IsAttached || args.Contains("--console"));
var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());
var host = builder.Build();

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

For installation of the service use the tool sc.exe. You can run the app as console app by passing --console as argument to the app. For debugging you need to pass --console as well.

In my case, I did have a "UseWindowsService()" statement included in my host builder setup. However, I have that configuration broken out across multiple lines and the problem was that, at some point during development, I had ALSO placed a:

UseConsoleLifetime()

statement into the mix further down in the code. Once I figured out what was going on, using the following partial code block resolved the issue:

        var hostBuilder = Host.CreateDefaultBuilder(args);
        if (WindowsServiceHelpers.IsWindowsService())
        {
            hostBuilder.UseWindowsService();
        }
        else
        {
            hostBuilder.UseConsoleLifetime();
        }

Note, WindowsServiceHelpers is a static class in the "Microsoft.Extensions.Hosting.WindowsServices" namespace.

Related