Skip to content

Instantly share code, notes, and snippets.

@scheffler
Last active August 7, 2020 13:34
Show Gist options
  • Save scheffler/012516cdba44b508df366f3637a1c0c5 to your computer and use it in GitHub Desktop.
Save scheffler/012516cdba44b508df366f3637a1c0c5 to your computer and use it in GitHub Desktop.
dotnet core fix configuration path when running as service
//
// When running a dotnet core console app from within a windows service, you may
// see that the service will not start. If you're using the default host builder it
// won't be able to find appsettings.json b/c your starting directory is not where it would
// be when you run interactively.
//
// Call the WindowsServiceHelpers:IsWindowsService to check to see if you're running in a service
// context and then force the current directory to the location of the exe.
//
using Serilog;
using Microsoft.Extensions.Hosting.WindowsServices;
namespace ServiceSample
{
class Program
{
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
// normal service setup stuff
});
static async Task Main(string[] args)
{
// Ensure that the appsettings can be found when run from a service context
if (WindowsServiceHelpers.IsWindowsService())
{
var pathToExe = Process.GetCurrentProcess().MainModule?.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot);
}
// Be sure to init logging after the directory set or your logs will be off
// in c:\Windows\System32
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("Logs/sample-log.txt", rollingInterval: RollingInterval.Month)
.CreateLogger();
var host = CreateHostBuilder(args).Build();
// Rest of your startup stuff goes here
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment