Home > OS >  Change environment variable RUN TIME
Change environment variable RUN TIME

Time:04-13

How can I change the environment variable RUN TIME? Using Login PAGE I am selecting Development or Production. Based on that I have to use my ConnectionString device specifically.

"ConnectionStrings": {
"PROJECTNAME_Development": "SERVER_DETAILS",
"PROJECTNAME_Production": "SERVER_DETAILS",
}

Here are my LoginServices.CS file

public class LoginService: ILoginService
{
        private readonly string _connectionString = string.Empty;
        private readonly IConfiguration _configuration;
}
public LoginService (IConfiguration configuration)
{
        _configuration = configuration;
        //If ADMIN SELECT Development
        _connectionString = _configuration.GetConnectionString("PROJECTNAME_Development");
        //If ADMIN SELECT Production
        _connectionString = _configuration.GetConnectionString("PROJECTNAME_Production");
}

UPDATE 1 I tried this code. It works fine but is there any other way like at one location I make a change and Environment Variable value gets updated.

My Controller

 [HttpPost]
        public IActionResult Login(LoginModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    model.DevelopmentServer = "Development";
                    // model.DevelopmentServer = "Production";
                    ...
                     var Result = ILoginService.AdminLogin(model);  
  
 public LoginService(IConfiguration configuration, IOptions<ConnectionStringDetails> connectionStrings)
        {
            _proDBCon = connectionStrings.Value.PROJECTNAME_Development;
            _proDBConProduction = connectionStrings.Value.PROJECTNAME_Production;
        }

In the same file LoginService.cs File

public LoginInfo AdminLogin(LoginModel model)
{
 if (model.DevelopmentServer == "Development") {
                _connectionString = _proDBCon;
            }
            else {
                _connectionString = _proDBConProduction;
            }
}

CodePudding user response:

Assuming that you need to switch between two databases from UI at any cost, you won't be able to complete it entirely using containers/injections. You have to use the value passed from UI to determine which database connection string should be used.

public class LoginService {
   // ...
   private string GetConnectionString(string connectionStringNameFromUi){
       return _configuration.GetConnectionString
   }
}

Meanwhile, I would consider deploying two separate instances of an application, one configured for dev and another for prod. In such way, you would get more out of the box (injections container and environment configuration).

  • Related