How to get setting from appsettings.json

William Buchanan 61 Reputation points
2022-12-22T04:27:09.63+00:00

Hi all

I am working in a Web API project. I have a class library in the solution. In this library I want to get a setting from the appSettings.json.

The only options I have seen so far seem to revolve around passing the IConfiguration object down from the web api. This is annoying.

Is there a way to just get the configuration in the class library without passing it in?

It used to be easy with the previous configuration settings - can't understand why it is so hard now...

Thanks

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-12-22T09:15:05.387+00:00

    Hi @William Buchanan ,

    In the Class Library, you can install the Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json package via NuGet.

    Then refer to the following code to add the appSettings.json file and read the configuration.

    public interface IDataRepository  
    {  
        string GetConnection();  
    }  
    
    public class DataRepository : IDataRepository  
    {  
        private readonly IConfiguration _config;  
        public DataRepository(IConfiguration configuration)  
        {  
            _config= configuration;  
        }  
        public string GetConnection()  
        {  
            string c = Directory.GetCurrentDirectory();  
            IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(c).AddJsonFile("appSettings.json").Build();  
            string connectionStringIs = configuration.GetConnectionString("WebApplication1Context");  
            return connectionStringIs;  
        }  
    }  
    

    In the API application, add the Class Library reference, and register the above repository.

    builder.Services.AddScoped<IDataRepository, DataRepository>();  
    

    In the appSetting.json file, add the connection string like this:

    "ConnectionStrings": {  
     "WebApplication1Context": "Server=(localdb)\\mssqllocaldb;Database=WebApplication1;Trusted_Connection=True;MultipleActiveResultSets=true"   
      },  
    

    Then, in the API controller, call the Class Library method:

    [ApiController]  
    public class UsersController : ControllerBase  
    {  
        private readonly IDataRepository _repo;  
        public UsersController(IDataRepository dataRepository)  
        {  
            _repo = dataRepository;  
        }  
    
        [HttpGet]  
        [Route("getconnectionstring")]  
        public IActionResult GetCurrentUserGroups()  
        {  
            var connection = _repo.GetConnection();  
            return Ok(connection);  
        }   
    }  
    

    The result as below:
    273241-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-12-22T17:09:26.09+00:00

    it considered a bad practice to tie a library to a configuration system and DI should be used instead. if you want static setup, define a config poco object for your library, and make it a static, that can be set in startup.

    1 person found this answer helpful.

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.