Hi i am following microsoft docs ...
in order to inject configurations as singleton in .NET Core Web API
Here is Program.cs code where i load my configurations:
public class Program
{
public static Dictionary<string, string> arrayDict =
new Dictionary<string, string>
{
{"connString", "Data Source =xxx/xxx;User Id =xxx;Password =xxx"}
};
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
builder.AddInMemoryCollection(arrayDict);
builder.AddJsonFile(
"appsettings.json", optional: false, reloadOnChange: false);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Here in Startup.cs i use following
public class Startup
{
private readonly IConfiguration Configuration;
public Startup(IConfiguration config)
{
Configuration = config;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<IConfiguration>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Still when i am using dependency injection in my Controller i am unable to inject IConfiguration, and get following error at invoking cotroller action (runtime error):
A suitable constructor for type 'IrisDotNetCore.Controllers.LoginController' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
LoginController.cs Code:
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
IConfiguration _configuration;
LoginController(IConfiguration configuration)
{
_configuration = configuration;
}
}
What is possibly wrong here?
IConfiguration
to begin with. That can be seen as a code smell. – Nkosi