AnKing
AnKing

Reputation: 2184

How to read appsettings.json values ASP.NET Core

After I've read this article about dependency injection Here I still do not have a clear understanding on how to read the appsetting in other than a controller classes.

Lets say for instance I have a helper class with a bunch of static methods that I'm planning to use, I do not create an instance of this class, how do I read setting values to use inside the methods of this class?

Upvotes: 1

Views: 3611

Answers (2)

Nick Mehrdad Babaki
Nick Mehrdad Babaki

Reputation: 12555

You should use services.Configure as below:

   public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
          services.Configure<JSonAsClass>(Configuration.GetSection("MySectionName"));
          services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

then you can inject JSonAsClass inside any class you want to use it:

        private JSonAsClass jSonAsClass;
        public MailService(IOptions<JSonAsClass> jSonAsClass)
        {
            this.jSonAsClass = jSonAsClass.Value;
        }

Upvotes: 2

Uriil
Uriil

Reputation: 12628

I used to create helper class to read data from appsettings.config in one of my applications:

public static class ConfigValueProvider
{
    private static readonly IConfigurationRoot Configuration;

    static ConfigValueProvider()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        Configuration = builder.Build();
    }

    public static string Get(string name)
    {
        return Configuration[name];
    }
}

However later I reviewed my application to get away from static methods which depends on application config in order to make my application testable.

Upvotes: 2

Related Questions