I am trying to dockerize an ASP.NET Core 5 Web API project and so I am going to transfer all configs from appSettings.json to docker-compose environment section. And then going to read them from environment section in a controller. How should do this?
I have tried to use IConfiguration and Environment in the controller, but I have just got Null.
My Program.cs is:
namespace Order.Api
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
}
And the StartUp.cs is:
namespace Order.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<OrderContext>(options =>
options.UseSqlServer(Configuration.GetValue<string>("ConnectionString")));
// options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
services.AddControllers();
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "Order.Api", Version = "v1"}); });
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Order.Api v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}
And the docker-compose.override is:
version: '3.4'
services:
Order.Api :
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://0.0.0.0:80
- ConnectionString=${ESHOP_AZURE_ORDERING_DB:-Server=sqldata;Database=Order;User Id=sa;Password=Pass@word}
- MyConfig=Active
ports:
- "5001:80"
sqldata :
environment:
- SA_PASSWORD=Pass@word
- ACCEPT_EULA=Y
ports:
- "5433:1433"
volumes:
- order-sqldata:/var/opt/mssql
volumes:
order-sqldata:
external: false