Chapter 2 of 8 · 4 practices · 2 min · 4-question quiz
Dependency injection and configuration
Choosing the right service lifetime, binding settings into validated options and keeping secrets out of appsettings.json.
Start: Never inject a scoped service into a singleton4 practices in this chapter
- 1Never inject a scoped service into a singletonEvery registration has a lifetime: The docs warn: do not resolve a scoped service from a singleton. The scoped service then lives as long as the singleton, a captive dependency, so one request's…
- 2Bind settings into options classes and validate them on startReading
IConfiguration["Payments:ApiKey"]in services spreads magic strings everywhere and fails only when that line runs. The options pattern binds a configuration section to a class and injects… - 3Keep secrets out of appsettings.json
appsettings.jsonis committed, so a connection string with a password in it is readable by everyone with repository access, forever. - 4Group registrations into extension methods per featureA
Program.cswith two hundredAddScopedlines is hard to read and causes merge conflicts. Group each feature's registrations into an extension method onIServiceCollection, next to the…
Check yourself on this chapter
4 questions, right here once you are signed in. Your progress is saved as you read.