Skip to content

Instantly share code, notes, and snippets.

@snickroger
Last active October 16, 2019 20:57
DI Demo - Better
var serviceCollection =
new ServiceCollection()
.AddSingleton<IWeatherServiceApi, UsWeatherServiceApi>()
.AddSingleton<IWeatherServiceApi, CanadaWeatherServiceApi>()
.AddSingleton<IWeatherServiceParser, UsWeatherServiceParser>()
.AddSingleton<IWeatherServiceParser, CanadaWeatherServiceParser>()
.AddSingleton<Func<string, IWeatherServiceApi>>(WeatherServiceApiFactory)
.AddSingleton<Func<string, IWeatherServiceParser>>(WeatherServiceParserFactory)
.AddSingleton<TextWriter>(Console.Out)
.AddSingleton<TextReader>(Console.In)
.AddSingleton<IWeatherService, WeatherService>()
.AddSingleton<IDIDemoService, DIDemoService>();
...
private static Func<IServiceProvider, Func<string, IWeatherServiceApi>> WeatherServiceApiFactory =>
service =>
{
return
postalCode =>
{
if (IsUsZipCode(postalCode))
{
return service.GetServices<IWeatherServiceApi>().First(s => s is UsWeatherServiceApi);
}
if (IsCanadianPostalCode(postalCode))
{
return service.GetServices<IWeatherServiceApi>().First(s => s is CanadaWeatherServiceApi);
}
throw new ArgumentException("Could not determine location");
};
};
private static Func<IServiceProvider, Func<string, IWeatherServiceParser>> WeatherServiceParserFactory =>
service =>
{
return
postalCode =>
{
if (IsUsZipCode(postalCode))
{
return service.GetServices<IWeatherServiceParser>().First(s => s is UsWeatherServiceParser);
}
if (IsCanadianPostalCode(postalCode))
{
return service.GetServices<IWeatherServiceParser>().First(s => s is CanadaWeatherServiceParser);
}
throw new ArgumentException("Could not determine location");
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment