Created
September 24, 2020 09:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"PlanetConfiguration": { | |
"Planets": [ | |
{ | |
"Name": "Green Aliens on Mars", | |
"Code": "MARS", | |
"Id": 111000111 | |
}, | |
{ | |
"Name": "Pluto the outcast", | |
"Code": "PLTO", | |
"Id": 969111969 | |
} | |
] | |
}, | |
"AllowedHosts": "*" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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! | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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