IConfiguration does not contain a definition for GetValue
Asked Answered
B

2

213

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?

Brashy answered 19/2, 2019 at 13:43 Comment(0)
B
441

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.

Brashy answered 19/2, 2019 at 13:43 Comment(0)
C
47

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"] + "/";
Casias answered 12/4, 2021 at 17:38 Comment(4)
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. – Brashy
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 :) – Susie
The advantage of this version is that it requires one less dependency. So it's my default choice for simple things like console applications. – Hoax
Yeah, I actually think this approach is better than my initial one. πŸ˜‰ Just be aware of .NET versions and compatibility. – Brashy

© 2022 - 2024 β€” McMap. All rights reserved.