Search code examples
c#service.net-8.0aspnetcore-environment

using ASPNETCORE_ENVIRONMENT in a .NET 8 service application


I have built a service that will be used at many client sites. I would like the service to use the ASPNETCORE_ENVIRONMENT variable to select the appropriate settings for the client server it is running on. ie connection string. I thought i could just create another appsettings..json file. This doesn't work with the default code. Please point me in the right direction. Thanks in advance.

using DbService.Models;
using Microsoft.EntityFrameworkCore;
using RmsEmailService;
using RmsEmailService.Services;

var builder = Host.CreateDefaultBuilder(args).ConfigureServices((hostContext, services) =>
{
    services.AddDbContext<RMSContext>(options =>
        options.UseSqlServer(hostContext.Configuration.GetConnectionString("DefaultConnection")));
    services.AddWindowsService();
    services.AddScoped<LoadListService>();
    services.AddScoped<PackingHeaderService>();
    services.AddScoped<BolItemService>();
    // Register your worker service
    services.AddHostedService<Worker>();
});

var host = builder.Build();
host.Run();

Solution

  • ASPNETCORE_ENVIRONMENT is for ASP.NET Core projects, use DOTNET_ENVIRONMENT instead for non-web projects with hosting (though in some cases for ASP.NET Core DOTNET_ENVIRONMENT will have higher precedence then ASPNETCORE_ENVIRONMENT - see the Environments section of the docs).