Home > Mobile >  How can i get IConfiguration (injection dependency) in controller with .NET6
How can i get IConfiguration (injection dependency) in controller with .NET6

Time:07-29

I am trying to get IConfiguration in controller api with .NET6 . Ihave this Program.cs:

var builder = WebApplication.CreateBuilder(args);

var config = builder.Configuration;


// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<IConfiguration>(config);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}


app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();


app.Run();

And i have this controller:

[Route("api/[controller]")]
    [ApiController]
    public class PeriodsController : ControllerBase
    {
        IConfiguration conf;
        PeriodsController(IConfiguration _conf)
        {
            conf = _conf;
        }
        // GET: api/Periods
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
}

That does not work. How can i get IConfiguration using injection dependency??

I receive this error:

A suitable constructor for type 'xxxx.Controllers.PeriodsController' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments

CodePudding user response:

You need to make the constructor public:

[Route("api/[controller]")]
[ApiController]
public class PeriodsController : ControllerBase
{
    IConfiguration conf;
    public PeriodsController(IConfiguration _conf)
    {
        conf = _conf;
    }
    // ...
}
  • Related