Skip to content

Instantly share code, notes, and snippets.

@stand-sure
Created October 17, 2023 21:19
Show Gist options
  • Save stand-sure/948d39930ead22a5904b96b051e1d898 to your computer and use it in GitHub Desktop.
Save stand-sure/948d39930ead22a5904b96b051e1d898 to your computer and use it in GitHub Desktop.
POCO Config w/o IOptions
// 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