2

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.

0

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

4 Comments

using this solution is get the following error: System.NullReferenceException: 'Object reference not set to an instance of an object.' I have posted what worked for me as the answer.
You need to use using Microsoft.Extensions.Configuration;
i did and the error above still occurred. Anyway its ok. I got the solution thanks for the help.
I managed to make your solution work. I had to add the following constructor in order to make it functional: public PeriodicExecutor(IConfiguration configuration){ Configuration = configuration;} if you edit your answer I can accept it.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.