Created
October 17, 2023 21:19
-
-
Save stand-sure/948d39930ead22a5904b96b051e1d898 to your computer and use it in GitHub Desktop.
POCO Config w/o IOptions
This file contains hidden or 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
// found at https://www.strathweb.com/2016/09/strongly-typed-configuration-in-asp-net-core-without-ioptionst/ | |
public static class ServiceCollectionExtensions | |
{ | |
public static TConfig ConfigurePOCO<TConfig>(this IServiceCollection services, IConfiguration configuration, Func<TConfig> pocoProvider) where TConfig : class | |
{ | |
if (services == null) throw new ArgumentNullException(nameof(services)); | |
if (configuration == null) throw new ArgumentNullException(nameof(configuration)); | |
if (pocoProvider == null) throw new ArgumentNullException(nameof(pocoProvider)); | |
var config = pocoProvider(); | |
configuration.Bind(config); | |
services.AddSingleton(config); | |
return config; | |
} | |
public static TConfig ConfigurePOCO<TConfig>(this IServiceCollection services, IConfiguration configuration, TConfig config) where TConfig : class | |
{ | |
if (services == null) throw new ArgumentNullException(nameof(services)); | |
if (configuration == null) throw new ArgumentNullException(nameof(configuration)); | |
if (config == null) throw new ArgumentNullException(nameof(config)); | |
configuration.Bind(config); | |
services.AddSingleton(config); | |
return config; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment