ChatGPT解决这个技术问题 Extra ChatGPT

IConfiguration does not contain a definition for GetValue

After moving a class through projects, one of the IConfiguration methods, GetValue<T>, stopped working. The usage is like this:

using Newtonsoft.Json;
using System;
using System.Net;
using System.Text;
using Microsoft.Extensions.Configuration;

namespace Company.Project.Services
{
    public class MyService
    {
        private readonly IConfiguration _configuration;

        public string BaseUri => _configuration.GetValue<string>("ApiSettings:ApiName:Uri") + "/";

        public MyService(
            IConfiguration configuration
        )
        {
            _configuration = configuration;
        }
    }
}

How can I fix it?


P
Pang

Just install Microsoft.Extensions.Configuration.Binder and the method will be available.

The reason is that GetValue<T> is an extension method and does not exist directly in the IConfiguration interface.


J
Jordan Ryder

The top answer is the most appropriate here. However another option is to get the value as a string by passing in the key.

public string BaseUri => _configuration["ApiSettings:ApiName:Uri"] + "/";

This does not answers the question, because it specifically asks for how to fix that method. Although this is a good alternative for the initial approach, thanks.
Hey Jordan. Just wanted to thank you for posting this. Even though your reply may not directly answer the question, it does provide a decent alternative. I came here from google and I am now considering your way of retrieving settings. So I would consider your answer a valuable addition to this thread. Thanks mate :)
The advantage of this version is that it requires one less dependency. So it's my default choice for simple things like console applications.
Yeah, I actually think this approach is better than my initial one. 😉 Just be aware of .NET versions and compatibility.