Skip to content

Instantly share code, notes, and snippets.

@romeshniriella
Created September 24, 2020 09:26
Show Gist options
  • Save romeshniriella/e0205324052cb0370a3e5cf407313728 to your computer and use it in GitHub Desktop.
Save romeshniriella/e0205324052cb0370a3e5cf407313728 to your computer and use it in GitHub Desktop.
.Net Core DI - Register a complex object with an array of more objects
{
"PlanetConfiguration": {
"Planets": [
{
"Name": "Green Aliens on Mars",
"Code": "MARS",
"Id": 111000111
},
{
"Name": "Pluto the outcast",
"Code": "PLTO",
"Id": 969111969
}
]
},
"AllowedHosts": "*"
}
public class PlanetConfiguration
{
public List<Planet> Planets { get; set; }
public class Planet
{
public string Code { get; set; }
public int Id { get; set; }
public string Name { get; set; }
}
}
// example usage
public class PlantRotator
{
private readonly PlanetConfiguration _config;
public PlantRotator(IOptions<PlanetConfiguration> configOptions){
_config = configOptions.Value;
}
public void Rotate(){
foreach (var planet in _config.Planets)
{
// rotate this!
}
}
}
public static class ServiceCollectionExtensions
{
public static IServiceCollection RegisterTransactionHandlers(this IServiceCollection services, IConfiguration configuration)
{
// notice in the json file, the root object has the same name as the config class
services.Configure<PlanetConfiguration>(configuration.GetSection("PlanetConfiguration"));
return services;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment