How to setup Configuration in Class file?

wavemaster 311 Reputation points
2021-06-08T16:24:58.143+00:00

I would like to move these two "secrets" to secrets.json
@inject IConfiguration config does not work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Extensions.Configuration;



/// <summary>
/// Summary description for TwilioAutomation
/// </summary>
namespace MyTwilio
{
    public class TwilioAutomation
    {
        public static Twilio.TwilioRestClient MySender()
        {
            string sid = "aaaaaa";
            string token = "bbbbbb";

            return new Twilio.TwilioRestClient(sid, token);
        }

        public class SMS_Message
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,577 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 28,291 Reputation points
    2021-06-08T21:13:59.51+00:00

    Use the following service pattern. The official Core docs cover this service pattern and dependency injection. Again, I'm using the appsettings.json file in wwwroot. You can use whatever file you like. Keep in mind, any custom file must be registered in configuration. See the official docs.

        public interface ITwilioAutomation  
        {  
            string GetToken();  
        }  
      
        public class TwilioAutomation : ITwilioAutomation  
        {  
            private readonly string sid;  
            private readonly string token;  
            public TwilioAutomation(IConfiguration config)  
            {  
                sid = config.GetSection("Twilio:sid").Value;  
                token = config.GetSection("Twilio:token").Value;  
            }  
      
            public string GetToken()  
            {  
                return token;  
            }  
        }  
    

    Register the service in the program.cs file.

    builder.Services.AddScoped<ITwilioAutomation, TwilioAutomation>();  
    

    Implementation

    @page "/"  
    @inject BlazorWasm.Services.ITwilioAutomation twilio  
      
    Welcome to your new app.  
      
    <SurveyPrompt Title="How is Blazor working for you?" />  
      
    <div>  
        @twilio.GetToken()  
    </div>  
      
    @code {  
      
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.