Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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