Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ObjectOrientatedNamedServiceProviderDemo
private static IServiceProvider GetServiceProvider()
{
var services = new ServiceCollection();
services.AddSingleton<CentigradeToKelvinMapper>();
services.AddSingleton<FahrenheitToKelvinMapper>();
services.AddSingleton<RankineToKelvinMapper>();
services.AddSingleton<KelvinToKelvinMapper>();
services.AddSingleton<KelvinConverterMapper>(provider => key =>
{
switch ((string.IsNullOrEmpty(key) ? " " : key).ToUpper()[0])
{
case 'C':
return provider.GetRequiredService<CentigradeToKelvinMapper>();
case 'F':
return provider.GetRequiredService<FahrenheitToKelvinMapper>();
case 'R':
return provider.GetRequiredService<RankineToKelvinMapper>();
case 'K':
return provider.GetRequiredService<KelvinToKelvinMapper>();
default:
return null;
}
});
services.AddSingleton<TemperatureCalculator>();
return services.BuildServiceProvider();
}
private class CentigradeToKelvinMapper : IKelvinMapper
{
public decimal ToKelvins(decimal value) => value + 273.15M;
}
private class FahrenheitToKelvinMapper : IKelvinMapper
{
public decimal ToKelvins(decimal value) => (value + 459.67M) * 5 / 9;
}
private class RankineToKelvinMapper : IKelvinMapper
{
public decimal ToKelvins(decimal value) => value * 5 / 9;
}
private class KelvinToKelvinMapper : IKelvinMapper
{
public decimal ToKelvins(decimal value) => value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment