'Blazor : How to read appsetting.json from a class in .NET 6?

The following is working for me, but not sure this is the right way to do use DI in .NET6 blazor.

I have the following class

public class Authentication
{
 
    private IConfiguration _configuration;
    private AppState _appState;

    public Authentication(IConfiguration Configuration, AppState appState)
    {
        _configuration = Configuration;
        _appState = appState; ;
    }
    public async Task<AccessToken?> getAccessToken()
    {
                             
        var tokenServer = _configuration.GetValue<string>("tokenUrl"); 
        var clientID = _configuration.GetValue<string>("ABC:ClientID");
        var clientSecret = _configuration.GetValue<string>("ABC:ClientSecret");
        var grantType = _configuration.GetValue<string>("ABC:GrantType");
        AccessToken? accessToken = null;
    .............
    ............
        return accessToken;
    }
}

in my code behind of razor page

namespace XXXXXXXXXXX.Pages
 {
public partial class Index
{
    [Inject]
    public ILogger<Index> _Logger { get; set; }

    [Inject]
    public IConfiguration Configuration { get; set; }

    [Inject]
    public AppState _appState { get; set; }

    **Authentication auth;**

    
    protected override void OnInitialized()
    {
        **auth = new Authentication(Configuration, _appState);**
        base.OnInitialized();
    }
    private async Task HandleValidSubmit()
    {
        _Logger.LogInformation("HandleValidSubmit called");
        auth.getAccessToken();

        // Process the valid form
    }

    
}
 }

My Question is I was Expecting the DI to do its magic and Insert the Dependency in my class.

but to get this working i had to write

auth = new Authentication(Configuration, _appState);

I was expecting to instantiate using auth = new Authentication() , but this one throws compiler error.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source