10 Service configuration with dependency injection

 

This chapter covers

  • Understanding the benefits of dependency injection
  • How ASP.NET Core uses dependency injection
  • Configuring your services to work with dependency injection
  • Choosing the correct lifetime for your services

In part 1 of this book, you saw the bare bones of how to build applications with ASP.NET Core. You learned how to compose middleware to create your application and how to use the MVC pattern to build traditional web applications with Razor Pages and Web APIs. This gave you the tools to start building simple applications.

In this chapter you’ll see how to use dependency injection (DI) in your ASP.NET Core applications. DI is a design pattern that helps you develop loosely coupled code. ASP.NET Core uses the pattern extensively, both internally in the framework and in the applications you build, so you’ll need to use it in all but the most trivial of applications.

You may have heard of DI before, and possibly even used it in your own applications. If so, this chapter shouldn’t hold many surprises for you. If you haven’t used DI before, never fear; I’ll make sure you’re up to speed by the time the chapter is done!

This chapter starts by introducing DI in general, the principles it drives, and why you should care about it. You’ll see how ASP.NET Core has embraced DI throughout its implementation and why you should do the same when writing your own applications.

10.1 Introduction to dependency injection

10.1.1 Understanding the benefits of dependency injection

10.1.2 Creating loosely coupled code

10.1.3 Dependency injection in ASP.NET Core

10.2 Using the dependency injection container

10.2.1 Adding ASP.NET Core framework services to the container

10.2.2 Registering your own services with the container

10.2.3 Registering services using objects and lambdas

10.2.4 Registering a service in the container multiple times

10.2.5 Injecting services into action methods, page handlers, and views

10.3 Understanding lifetimes: When are services created?

10.3.1 Transient: Everyone is unique

10.3.2 Scoped: Let’s stick together

10.3.3 Singleton: There can be only one

10.3.4 Keeping an eye out for captured dependencies