Skip to content

Instantly share code, notes, and snippets.

@configureappio
Created January 19, 2020 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save configureappio/32de0b4a10a963c50c931c4494cfa167 to your computer and use it in GitHub Desktop.
Save configureappio/32de0b4a10a963c50c931c4494cfa167 to your computer and use it in GitHub Desktop.
FunctionalNamedServiceProviderDemo
private static class ServiceBuilder
{
private static readonly Lazy<IServiceProvider> Instance = new Lazy<IServiceProvider>(GetServiceProvider);
public static IServiceProvider Get() => Instance.Value;
private static IServiceProvider GetServiceProvider()
{
var services = new ServiceCollection();
services.AddSingleton<KelvinConverterMapper>(provider => (tempScale, temp) =>
{
switch ((string.IsNullOrEmpty(tempScale) ? " " : tempScale).ToUpper()[0])
{
case 'C':
return CentigradeToKelvins(temp);
case 'F':
return FahrenheitToKelvins(temp);
case 'R':
return RankineToKelvinMapper(temp);
case 'K':
return KelvinsToKelvins(temp);
default:
throw new KeyNotFoundException($"Unknown scale '{tempScale}'");
}
});
services.AddSingleton<TemperatureCalculator>();
return services.BuildServiceProvider();
}
private static decimal CentigradeToKelvins(decimal value) => value + 273.15M;
private static decimal FahrenheitToKelvins(decimal value) => (value + 459.67M) * 5 / 9;
private static decimal RankineToKelvinMapper (decimal value) => value * 5 / 9;
private static decimal KelvinsToKelvins(decimal value) => value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment