In my docker-compose.yaml
, I'm setting environment variables to an api service with
env_file:
- db.env
db.env
MYSQL_DATABASE=db_name
MYSQL_ROOT_PASSWORD=root
MYSQL_USER=user
MYSQL_PASSWORD=pass
How to access them to connect to the database with a string like this?
string _connectionString = $"server={Env["MYSQL_SERVER_NAME"]}; database={Env["MYSQL_DATABASE"]}; user={Env["MYSQL_USER"]}; password={Env["MYSQL_PASSWORD"]}";
CodePudding user response:
This is an invaluable reference: Configuration in .Net - essentially, a lot of the plumbing is already done for you.
So, if for example you wanted to set that in your startup Program.cs
:
var builder = WebApplication.CreateBuilder(args);
....
string _connectionString = $"server={builder.Configuration["MYSQL_SERVER_NAME"]}...
With DI, in a MVC controller for example:
public class SomeController: Controller
{
public SomeController(ILogger<HomeController> logger, IConfiguration configuration)
{
string _connectionString = $"server={configuration["MYSQL_SERVER_NAME"]}....
In a Razor Page:
public class HelloModel: PageModel
{
public HelloModel(ILogger<HomeController> logger, IConfiguration configuration)
{
string _connectionString = $"server={configuration["MYSQL_SERVER_NAME"]}....
Hth..