Friday, April 10, 2020

Access config settings using custom class

In the previous post we saw on how to use Dependency Injection to get the configuration options in the Controller classes. In this post we will see another way of reading the configuration setting using a custom class.
In this option we create a custom class for a section of the configuration and the class will have one property for each configuration key in the config file. The config settings are loaded to the class at startup and later we just have to reference the property to get the config value.  This option might need a code change to the class every time we add or modify configuration settings. 

In the below sample, we create a class AppSetting which maps to the section ApplicationSettings in the appsettings.json configuration file. The config class is injected at startup and is available to other service / controller classes in the application.

public class AppSettings
{
    public string ConnectionString { get; set; }
}

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

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
        services.Configure<AppSettings>(Configuration.GetSection("ApplicationSettings"));
    }
}

Once we initialize the config settings class in the Startup, we can access the injected config settings class in the controller as follows.

[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
    private AppSettings appSettings;
    private IExamService _examService;
    public ExamController(IOptions<AppSettings> settings)
    {
        this.appSettings = settings.Value;
    }
}


Search Flipkart Products:
Flipkart.com

No comments: