ASP.NET Core Best Practices

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 singleton

4 practices in this chapter

  1. 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…
  2. 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…
  3. 3Keep secrets out of appsettings.jsonappsettings.json is committed, so a connection string with a password in it is readable by everyone with repository access, forever.
  4. 4Group registrations into extension methods per featureA Program.cs with two hundred AddScoped lines is hard to read and causes merge conflicts. Group each feature's registrations into an extension method on IServiceCollection, next to the…

Check yourself on this chapter

4 questions, right here once you are signed in. Your progress is saved as you read.

Sign up for the quiz