first of all I am a very beginner with dependency injection. I am trying to read appsettings.json configuration values from one of my class
here is my code
private readonly IConfiguration _configuration;
public AdoExtract(IConfiguration configuration = null)
{
_configuration = configuration;
}
public List<ApiAdoProject> ExtractAllWorkitems()
{
List<ApiAdoProject> projects = new List<ApiAdoProject>();
projects = GetAllProjects();
return projects;
//foreach (var prj in projects)
//{
// string s = prj.name;
//}
}
List<ApiAdoProject> GetAllProjects()
{
Uri uri = new Uri("https://dev.azure.com/****");
VssBasicCredential credentials =
new VssBasicCredential("", _configuration["PAT"]);
using (ProjectHttpClient projectHttpClient =
new ProjectHttpClient(uri, credentials))
{
IEnumerable<TeamProjectReference> projects =
projectHttpClient.GetProjects().Result;
}
return null;
}
When I run this _configuration["PAT"] returning null
Here is my appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"PAT": "mypat",
"ClientId": "567567567567546",
"ClientSecret": "",
"ConnectionStrings": {
"EpmoDb": "mycd"
}
}
Here is my startup
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
Code which use adocontroller
namespace EPMO_Toolset_API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AdoController : ControllerBase
{
private readonly IConfiguration _configuration;
public AdoController(IConfiguration configuration = null)
{
_configuration = configuration;
}
// GET: api/<AdoController>
[HttpGet]
public List<ApiAdoProject> Get()
{
AdoExtract ado = new AdoExtract();
return ado.ExtractAllWorkitems();
}
Did I missed anything or what I did wrong
var result = _configuration["PAT"];,for me, this code worked well,you can test it in your controller.I think you have done nothing wrong, there may be a problem elsewhereConfiguresServicesin startup (AdoExtract has to be registered), and also show the class that uses AdoExtract; how does an instance of AdoExtract come to be a thing that class can use?