9 Registering services with dependency injection

 

This chapter covers

  • Configuring your services to work with dependency injection
  • Choosing the correct lifetime for your services

In chapter 8 you learned about dependency injection (DI) in general, why it’s useful as a pattern for developing loosely coupled code, and its central place in ASP.NET Core. In this chapter you’ll build on that knowledge to apply DI to your own classes.

You’ll start by learning how to configure your app so that the ASP.NET Core framework can create your classes for you, removing the pain of having to create new objects manually in your code. We look at the various patterns you can use to register your services and some of the limitations of the built-in DI container.

Next, you’ll learn how to handle multiple implementations of a service. You’ll learn how to inject multiple versions of a service, how to override a default service registration, and how to register a service conditionally if you don’t know whether it’s already registered.

In section 9.4 we look at how you can control for how long your objects are used—that is, their lifetime. We explore the differences among the three lifetime options and some of the pitfalls to be aware of when you come to write your own applications. Finally, in section 9.5 you’ll learn why lifetimes are important when resolving services outside the context of an HTTP request.

9.1 Registering custom services with the DI container

9.2 Registering services using objects and lambdas

9.3 Registering a service in the container multiple times

9.3.1 Injecting multiple implementations of an interface

9.3.2 Injecting a single implementation when multiple services are registered

9.3.3 Conditionally registering services using TryAdd

9.4 Understanding lifetimes: When are services created?

9.4.1 Transient: Everyone is unique

9.4.2 Scoped: Let’s stick together

9.4.3 Singleton: There can be only one

9.4.4 Keeping an eye out for captive dependencies

9.5 Resolving scoped services outside a request

sitemap