TriedAtLeast
TriedAtLeast

Reputation: 301

How to access appsettings.json data in Blazor Server

I am trying to access the data stored in the appsettings.json file in a background service in my blazor server app but most illustrations of how to do this online are based on the Webassembly configuration of Blazor. I think I'm suppossed to use the Microsoft.Extensions.Configuration package but I can't quite figure out how to implement it.

Below is the background service with the essential code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using System.Timers;
using log4net;
using System.Net;
using System.IO;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;

namespace BlazorServerApp
{
    public class JobExecutedEventArgs : EventArgs { }
    public class PeriodicExecutor : IDisposable
    {
        Timer _Timer;
        bool _Running;

        public void StartExecuting()
        {
            if (!_Running)
            {
                // Initiate a Timer
                _Timer = new Timer();
                _Timer.Interval = 5000;
                _Timer.Elapsed += HandleTimer;
                _Timer.AutoReset = true;
                _Timer.Enabled = true;

                _Running = true;
            }
        }
        void HandleTimer(object source, ElapsedEventArgs e)
        {
            // Execute required job
            //connect to the appropriate SQL database
            var connectionString = "connection";
            //create connection variables for the two main SQL operations we will be doing
            using var connectionUpdate = new SqlConnection(connectionString);
            using var connectionCreate = new SqlConnection(connectionString);
            while (true)
            {
                Parallel.Invoke(
                () => createSurveyQueueEntries(connectionCreate),
                () => updateSurveyQueue(connectionUpdate));
            }
            // Notify any subscribers to the event
            OnJobExecuted();
        }
        public void Dispose()
        {
            if (_Running)
            {
                _Timer?.Dispose();
            }
        }

    }
}

I would like to take the connectionString defined in appsetting.json and use it to set the connectionString variable in the HandleTimer() method.

Below is the appsettings.json file

{
  "connectionString": "connection",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Any detailed guidance would be greatly appreciated.

Upvotes: 2

Views: 12383

Answers (2)

Nb777
Nb777

Reputation: 2032

If you are working in some class for example like creating a service, you need to add IConfiguration in the constructure:

using Microsoft.Extensions.Configuration;

private readonly IConfiguration configuration;
public PeriodicExecutor(IConfiguration configuration)
{             
 this.configuration = configuration;
}
 //Then you can use it 
var connection=  configuration["connectionString"];

If you have a razor component then you need to Inject IConfiguration like this:

using Microsoft.Extensions.Configuration;

[Inject]
private IConfiguration configuration { get; set; }
//then you can get your connectionString
var connection=  configuration["connectionString"];

You can read more about this

Upvotes: 12

TriedAtLeast
TriedAtLeast

Reputation: 301

The following solution, aside from the one above, also works: First install this package:

using Microsoft.Extensions.Configuration;

Then add the following line of code at the top of the class:

private static readonly IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").AddEnvironmentVariables().Build(); 

And then you can access the stored data using the key like so:

var connectionString = config.GetValue<string>("keyname");

Check the following link for more information: https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration

Upvotes: 3

Related Questions