1

I made an asp.net core project,but i have question,how override app-setting values after container built? my appsetting:

  "AppSetting": {
    "RabbitMqUrl": "rabbitmq://localhost/",
    "RabbitMqUserName": "guest",
    "RabbitMqPassword": "guest",
    "LoginMessage": "x",
    "ResetPasswordMessage": "x",
    "myval": 10
  }

I find this command but i want see and change myval value when container is running in for example in restart container command,how do these items?

   docker run -it -p 5005:5005 -e "AppSetting:myval=123" identity

1 Answer 1

1

UPDATE: After some clearification, question is about changing environment vars run-time. That is not a very good idea. For sharing application-wide variables that may change, a cache is a viable solution.

In Startup#ConfigureServices

services.AddDistributedMemoryCache();

Then you can inject

IMemoryCache

into your code. You can add/change cache value like this

_cache.Set("myval", 123, DateTimeOffset.MaxValue);

and the value will stay in cache until end of time (or until your code changes/removes it). You fetch data from cache like this

var myVal = 0;
if (_cache.TryGetValue("myval", out int value))
{
   myVal = value;
}

If you need to initialize the cache with some value from appsettings.json, that can be done inside Program#Main after webHost is built, and before calling webHost.Run / webHost.RunAsync.

END of update


Unless you have a class called AppSetting, json should look like below. You should have an appsettings.json that applies to all environments, an appsettings.Staging.json for staging, and an appsettings.Production.json for production.

{
  "RabbitMqUrl": "rabbitmq://localhost/",
  "RabbitMqUserName": "guest",
  "RabbitMqPassword": "guest",
  "LoginMessage": "x",
  "ResetPasswordMessage": "x",
  "myval": 10
}

You select running enviroment in Docker file like this

ENV ASPNETCORE_ENVIRONMENT Production

You can override parameters in appsettings.json like this

 ENV ASPNETCORE_myval 123

If you stick with your original JSON structure:

ENV ASPNETCORE_AppSetting__myval 123
Sign up to request clarification or add additional context in comments.

2 Comments

thanks roar, i want this value change in runtime or like this command docker run -it -p 5005:5005 -e "AppSetting:myval=123" identity ,i dont want create new instanse from my image ,but apply this change on current container.
@Ali.goodarzi: Ok, sorry for the misunderstanding. But you should not do it like that, settings are static stuff that is used for getting the app up-and-running. I will update my answer with more code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.