Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

WorkerService1

To get the windows background service to work successfully:

Add ServerGarbageCollection property to the csproj file as described here.

Install Microsoft.Extensions.Hosting as described here.

With Microsoft.Extensions.Hosting you can call UseWindowsService() when creating the host builder or add services.AddSingleton<IHostLifetime, WindowsServiceLifetime>(); to the services when creating a WebHostBuilder.

When publishing: set deployment-mode to Self-contained and check the produce single file and enable ReadyToRun compilation boxes as described here.

Running as a webhost

ServiceBase.Run needs to be called when running as a webhost by passing the WebHost into a WebHostService and then passing into ServiceBase.Run

See this

At the beginning of main

var isService = !(Debugger.IsAttached || args.Contains("--console"));

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

When running the webhost

if (isService)
{
    var webHostService = new WebHostService(webHost.Build());
    ServiceBase.Run(new ServiceBase[] { webHostService });
}
else
{
    await webHost.Build().RunAsync();
}

If adding SignalR and need to listen on localhost:

When injecting a HttpClient set the HttpClientHandler ServerCertificateCustomValidationCallback as described here and here

services.AddHttpClient<IHttpClientService, HttpClientService>().ConfigurePrimaryHttpMessageHandler(() =>
{
  var httpClientHandler = new HttpClientHandler
  {
    ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
  };

  return httpClientHandler;
});

Also, when creating a HubConnectionBuilder and adding the Url (.WithUrl) set the options like so to bypass the SSL certificate.

  options.WebSocketConfiguration = configuration =>
  {
    configuration.RemoteCertificateValidationCallback = (message, cert, chain, errors) => { return true; };
  };

  options.HttpMessageHandlerFactory = factory =>
  {
    if (factory is HttpClientHandler clientHandler)
      // bypass SSL certificate
      clientHandler.ServerCertificateCustomValidationCallback +=
        (sender, certificate, chain, sslPolicyErrors) => { return true; };

    return factory;
  };

About

The .Net 6 WorkerService template which calls .UseWindowsService() on the Host.CreateDefaultBuilder(args) so that it can run as a windows service successfully.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages