Reputation: 4759
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
Upvotes: 0
Views: 348
Reputation: 74710
You wouldn't do this:
AdoExtract ado = new AdoExtract();
Because that runs the AdoExtract constructor with a null IConfiguration, and it is AdoExtract that wants to use the configuration, so it can't be null
You would perhaps instead do something more like injecting the IAdoExtract into the controller:
public AdoController(IAdoExtract x)
And have registered the IAdoExtract to AdoExtract in your ConfigureServices, it means that the configured instance will be used because the DI creates the AdoExtract, it sees that it needs an IConfiguration and it knows how to provide it. If you create the AdoExtract yourself you're bypassing this and provding a null configuration instead
public void ConfigureServices(IServiceCollection services)
{
...
// decide a suitable lifetime eg Transient/Scoped etc
services.AddScoped<IAdoExtract, AdoExtract>();
}
Upvotes: 2