Blog

Filter posts by Category Or Tag of the Blog section!

Access to configuration in asp.net core

Tuesday, 09 February 2016

While I was working with asp.net core, I encountered with getting the configuration setting from the JSON file and After searching on the web I found out that there would be different ways to do that. I tested the following one and it worked. There is a different configuration in each version of Asp.net core in the Main method of program class. you should put the following configuration in this sample in the main method because I didn’t test it with other configurations to ensure you.

 public static void Main(string[] args)

        {

            var host = new WebHostBuilder()

                .UseKestrel()

                .UseContentRoot(Directory.GetCurrentDirectory())

                .UseIISIntegration()

                .UseStartup<Startup>()

                .UseApplicationInsights()

                .Build();



            host.Run();

        }

Then create a class to keeping configuration and creating injection based on it, it's just a simple property:

  public class ConfgurationClass

    {

        public string ConnectionString { get; set; }

    }

Now, in the target class that you want to access your configuration, inject the above class:

public class TestController : Controller

    {

        private readonly ConfgurationClass _connectionStrings;



        public TestController(IOptions<ConfgurationClass> options)

        {

            _connectionStrings = options.Value;

        }



        public IActionResult Index()

        {

            var connectionsString = _connectionStrings.ConnectionString;

            return Ok();

        }

    }

Note that IOption<> is available in Version=1.1.1.0 and above.  But if you run the application now, you would get the injection Error because you haven’t configured DI yet. Put the following piece of code in Startup class to configure the injection:

        public IConfigurationRoot Configuration { get; }



        public Startup(IHostingEnvironment env)

        {

            var builder = new ConfigurationBuilder()

                .SetBasePath(env.ContentRootPath)

                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)

                .AddEnvironmentVariables();



            Configuration = builder.Build();

        }



        public void ConfigureServices(IServiceCollection services)

        {

            services.AddOptions();



            // Configure ConnectionStrings using config

            services.Configure<ConfgurationClass>(Configuration);

        }

Remember that appsettings.json is the file that we are reading the connectionString from. Have a nice time!

Category: Software

Tags: Asp.Net

comments powered by Disqus