I have a GameSettingOptions class like this:
public class GameSettingOptions
{
public int gameId { get; set; }
public string iconSize { get; set; }
public int sortOrder { get; set; }
public string[] chips { get; set; }
}
And I am trying to retrieve it from a service being set up like this:
public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
var builder = new ConfigurationBuilder()
.SetBasePath(environment.ContentRootPath)
.AddJsonFile("GameSettingOptions.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
services.Configure<GameSettingOptions>(Configuration.GetSection("GameSettings"));
}
This is my json object where game settings is an array:
{
"GameSettings": [
{
"gameId": 1,
"iconSize": "big",
"sortOrder": 6
},
{
"gameId": 2,
"iconSize": "small",
"sortOrder": 4
}
]
}
And this is how I am trying to retrieve it using this controller and dependency injection
public class GameSettingsControllers : ControllerBase
{
private readonly GameSettingOptions Options;
public GameSettingsControllers(IOptionsSnapshot<GameSettingOptions> options)
{
Options = options.Value;
}
public object GetGameSettings()
{
return new JsonResult($"gameId: {Options.gameId}, " + $"iconSize: {Options.iconSize}, "
+ $"sortOrder: {Options.sortOrder}, " + $"chips: {Options.chips} ");
}
}
What I have tried:
- Turning both service and the property that consumes the service into a List, this returns null
services.Configure<List<GameSettingOptions>>(Configuration.GetSection("GameSettings"));
IOptions<List<GameSettingOptions>>
- Create another class that have a collection of GameSettingOptions property, then I bind and inject the new class, this also returns null
public class GameSettings
{
public GameSettingsOptions[] AllGameSettings {get; set;}
}
public class GameSettingOptions
{
public int gameId { get; set; }
public string iconSize { get; set; }
public int sortOrder { get; set; }
public string[] chips { get; set; }
}
- For the controller I try to do a foreach of IOptions value but it said GameSetingsOptions foes not contain a public instance or definition of 'GetEnumerator'