Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core 3.1 Console App as a Windows Service

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.

like image 536
Brade Avatar asked Feb 27 '20 04:02

Brade


Video Answer


1 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();
like image 142
Brade Avatar answered Oct 03 '22 14:10

Brade