Last active
October 16, 2019 20:57
DI Demo - Better
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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