question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Windows Service does not take settings from appsettings.json

See original GitHub issue

I followed the pattern established in the article: https://docs.microsoft.com/en-us/dotnet/core/extensions/windows-service.

If I run my service from the command line it runs great, but if I run it as service it doesn’t seem to see the settings in appsettings.json. Would love some direction on this as there are several thing in the config that I don’t want to have to hard code.

Example of my my program.cs

var context = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("hosting.json", optional: true)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
    .AddCommandLine(args)
    .AddEnvironmentVariables()
    .Build();

var key = context[Constants.CONFIG_KEY_APPLICATION_INSIGHTS];

IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options => options.ServiceName = Constants.SERVICE_NAME)
    .ConfigureWebHostDefaults(
        webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            webBuilder.UseUrls(context[Constants.CONFIG_KEY_HUB_URL]);
        })
    .ConfigureServices(
        services =>
        {
            services.AddSignalR();
            services.AddHostedService<LprWindowsService>();

            services
        .AddDbContext<FlashvaletContext>(
            optionsBuilder => optionsBuilder.UseSqlServer(
                    Constants.FLASHVALET_CONNECTIONSTRING,
                    sqlOptions =>
                    {
                        sqlOptions.CommandTimeout(120);
                        sqlOptions.EnableRetryOnFailure();
                    }),
            ServiceLifetime.Singleton);

            services.AddSingleton<IFileSystemService, FileSystemService>();
            services.AddSingleton<IGenericRepository, FlashValetRepository>();
            services.AddSingleton<IKioskService, KioskService>();
            services.AddSingleton<ILprStrategyFactory, LprStrategyFactory>();
            services.AddSingleton<IVerificationService, VerificationService>();
        })
    .ConfigureLogging(
        logging =>
        {
            logging.ClearProviders();
            logging.AddConfiguration(context.GetSection("Logging"));
            logging.AddConsole();
            //var key = context[Constants.CONFIG_KEY_APPLICATION_INSIGHTS];
            if(string.IsNullOrEmpty(key) == false)
                logging.AddApplicationInsights(key);

            if (EventLog.SourceExists(Constants.SERVICE_NAME) == false)
                EventLog.CreateEventSource(Constants.SERVICE_NAME, Constants.SERVICE_NAME);

            EventLogSettings eventLogSettings = new EventLogSettings
            {
                SourceName = Constants.SERVICE_NAME,
                LogName = Constants.SERVICE_NAME
            };

            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventLog(eventLogSettings);
        })
    .Build();

await host.RunAsync();

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:13 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
MariovanZeistcommented, Dec 7, 2021

@JasonDWilson when you run this as a service the Directory.GetCurrentDirectory() will probably return something like 'C:\Windows\System32\' and not the location of your service. So it will not find your configuration files

0reactions
JasonDWilsoncommented, Dec 9, 2021

Sorry – yes its published as self contained.

Read more comments on GitHub >

github_iconTop Results From Across the Web

appSettings.json not read when launching .net core ...
The appSettings.json file is read when running from Visual studio or command line, but when the service dll is ran from the service...
Read more >
Does a change on appsettings.json require IIS restart?
The application must restart to load appsettings.json. Restarting IIS will work or restarting the specific application in IIS will work too.
Read more >
Configuration in ASP.NET Core
Learn how to use the Configuration API to configure AppSettings in an ASP.NET Core app.
Read more >
Host ASP.NET Core in a Windows Service
The app's default settings files, appsettings.json and appsettings. ... The registered service doesn't use the app's published output from ...
Read more >
Create Windows Service using BackgroundService - .NET
Learn how to create a Windows Service using the BackgroundService in .NET.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found