How can I set a default value to a property, reading it from my appsettings.json file, on a model that is instantiated by the .NET Core 3 framework?
I've created a repo (a completely new .NET Core 3 project) where I try to illustrate the problem: https://github.com/NelsonPRSousa/dependency-injection-default-constructor
API Action:
[HttpGet]
public IEnumerable<WeatherForecast> Get([FromQuery] FilteringRequestModel request)
{
var defaultType = request.Type;
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
Model:
public class FilteringRequestModel
{
/* Please note that we must have a parameterless constructor, since it's the framework responsability to instatiate this object
* when invoking this action: IEnumerable<WeatherForecast> Get([FromQuery] FilteringRequestModel request)
*/
public FilteringRequestModel()
{
//Type = System.Configuration.ConfigurationManager.AppSettings["DefaultTypeTopRated"];
}
public string Type { get; set; } = "top_rated"; // TODO: Read from appsettings
}