Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You need to make the constructor public:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading