简体   繁体   中英

.Net 5, appsettings.json not available in Program.cs?

I'm assuming that this is due to my lack of understanding with the new .NET 5.0 worker service architecture, but my connection string isn't being used in my dependency injection.

I know that my appsettings.json file is getting incorporated into the Configuration object correctly as I can pull the values from it in the constructor of my Worker object. However, my DbContext object isn't using the connection string from my appsettings.json file and the service user is trying to perform the DB connection.

Here is the configuration section of my Program.cs file.

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService<Worker>();
            services.AddDbContext<RailScale.Domain.RailScaleContext>(opts =>
            {
                // Could it be that this is just the wrong object to use to access
                // my configuration values???

                opts.UseSqlServer(hostContext.Configuration.GetValue<string>("ConnectionStrings:Webapps"));
            });
        });

However, when I try to make any database call it fails due to user credentials. The service user is being used to connect to DB, not the user/pass specified in the appsettings.json file.

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    try
    {
        LoadParameters();

        // I get the correct connection string value at this point, but the 
        // Context object is still using the service user account.

        WriteToLog(_configuration.GetValue<string>("ConnectionStrings:Webapps"));

        _ActiveConnections = new ConcurrentDictionary<int, DataListener>();

        while (!stoppingToken.IsCancellationRequested)
        {
            // This line throws an exception because the user can't login to database, it is not using
            // the credentials from the connection string above.

            var scalesToAutoStart = _context.Scales.Where(s => s.AutoStart == true).ToList();

            foreach (RailScale.Domain.Scale scale in scalesToAutoStart)
            {
                ActivateConnection(scale);
            }
        }
    }
    catch (Exception ex)
    {
        string YouMakeMeWantToCry = ex.Message;
    }
}

What am I doing wrong? Am I using dependency injection in the wrong way for a worker service?

Edit:

After trying the changes listed, I'm still not having any luck. My next step was to completely ignore dependency injection and just force it to work. THAT didn't work either!

var DbOpts = new DbContextOptionsBuilder<RailScale.Domain.RailScaleContext>();
DbOpts.UseSqlServer(_configuration.GetConnectionString("Webapps"));

_context = new Domain.RailScaleContext(DbOpts.Options);
    
var scalesToAutoStart = _context.Scales.Where(s => s.AutoStart == true).ToList();

Does anyone have an idea why my context would be using the NT AUTHORITY\SYSTEM user? I'm beginning to question my Context object...

Its nothing to do with your dependency injection i'd guess the connection string is just not being loaded correctly. To get the connection string try this:

_configuration.GetConnectionString("Webapps")

Also not sure if thats actually needed, might be just a habbit but try this to load the config:

        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
          .AddJsonFile("appsettings.Docker.json", optional: true, reloadOnChange:true)
          .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
          .AddEnvironmentVariables()
          .Build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM