8 An introduction to dependency injection

 

This chapter covers

  • Understanding the benefits of dependency injection
  • Seeing how ASP.NET Core uses dependency injection
  • Retrieving services from the DI container

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 create minimal API endpoints to handle HTTP requests. This part gave you the tools to start building simple API applications.

In this chapter you’ll see how to use dependency injection (DI)—a design pattern that helps you develop loosely coupled code—in your ASP.NET Core applications. 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 applications.

You may have heard of DI 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, never fear; I’ll make sure you’re up to speed by the time the chapter is done!

This chapter introduces 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. Finally, you’ll learn how to retrieve services from DI in your app.

8.1 Understanding the benefits of dependency injection

8.2 Creating loosely coupled code

8.3 Using dependency injection in ASP.NET Core

8.4 Adding ASP.NET Core framework services to the container

8.5 Using services from the DI container

Summary

sitemap