Friday, April 10, 2020

Access config settings from appsetting.json in Controller using DI

In the previous post we saw the options to read config setting values in Startup, in this post we shall see on how to get the config setting values in the controller. We will inject the configuration object to the service and the same will be made available in the Controller using Dependency Injection.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc;
    services.AddSingleton<IConfiguration>(Configuration);
}

Once we inject the Configuration object in the ConfigureServices method of Startup it will be made available in the controllers through Dependency Injection. We can access the injected configuration object in the Controller as follows.

    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private IUserService _userService;
        IConfiguration _configuration;
        //
        public UserController(IUserService userService, IConfiguration configuration)
        {
            _userService = userService;
            _configuration = configuration;
        }
        //
        [HttpGet]
        public ActionResult<Users> Login(string userName, string password)
        {
            var myConfig = _configuration["myConfigKey"];
            Console.WriteLine("myConfig: " + myConfig);
            var user = _userService.Login(userName, password);
            return user;
        }
    }


Search Flipkart Products:
Flipkart.com

No comments: