188

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?

Pang
  • 9,564
  • 146
  • 81
  • 122
Machado
  • 8,965
  • 6
  • 43
  • 46

2 Answers2

397

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Machado
  • 8,965
  • 6
  • 43
  • 46
42

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"] + "/";
Jordan Ryder
  • 2,336
  • 1
  • 24
  • 29
  • 2
    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. – Machado May 28 '21 at 03:37
  • 2
    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 :) – Martijn Aug 03 '21 at 12:00
  • 4
    The advantage of this version is that it requires one less dependency. So it's my default choice for simple things like console applications. – Jonathan Allen Dec 08 '21 at 20:52
  • 2
    Yeah, I actually think this approach is better than my initial one. Just be aware of .NET versions and compatibility. – Machado Jan 13 '22 at 14:01