Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 515
Machado Avatar asked Feb 19 '19 13:02

Machado


People also ask

Does not contain a definition for GetValue?

IConfiguration does not contain a definition for GetValue. Typically appears when you're using IConfiguration outside of an Asp.Net Core app. In fact, GetValue is an extension method, so the solution is to simply add the following package: 1. Install-Package Microsoft.Extensions.Configuration.Binder.

What is IConfiguration?

The IConfiguration is an interface for . Net Core 2.0. The IConfiguration interface need to be injected as dependency in the Controller and then later used throughout the Controller. The IConfiguration interface is used to read Settings and Connection Strings from AppSettings. json file.


2 Answers

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.

like image 107
Machado Avatar answered Oct 18 '22 06:10

Machado


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"] + "/";
like image 41
Jordan Ryder Avatar answered Oct 18 '22 06:10

Jordan Ryder