Dependency Injection Principles, Practices, and Patterns
eBook - ePub

Dependency Injection Principles, Practices, and Patterns

Mark Seemann, Steven van Deursen

Compartir libro
  1. 552 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Dependency Injection Principles, Practices, and Patterns

Mark Seemann, Steven van Deursen

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Summary Dependency Injection Principles, Practices, and Patterns teaches you to use DI to reduce hard-coded dependencies between application components. You'll start by learning what DI is and what types of applications will benefit from it. Then, you'll work through concrete scenarios using C# and the.NET framework to implement DI in your own projects. As you dive into the thoroughly-explained examples, you'll develop a foundation you can apply to any of the many DI libraries for.NET and.NET Core.Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology Dependency Injection (DI) is a great way to reduce tight coupling between software components. Instead of hard-coding dependencies, such as specifying a database driver, you make those connections through a third party. Central to application frameworks like ASP.NET Core, DI enables you to better manage changes and other complexity in your software. About the Book Dependency Injection Principles, Practices, and Patterns is a revised and expanded edition of the bestselling classic Dependency Injection in.NET. It teaches you DI from the ground up, featuring relevant examples, patterns, and anti-patterns for creating loosely coupled, well-structured applications. The well-annotated code and diagrams use C# examples to illustrate principles that work flawlessly with modern object-oriented languages and DI libraries. What's Inside

  • Refactoring existing code into loosely coupled code
  • DI techniques that work with statically typed OO languages
  • Integration with common.NET frameworks
  • Updated examples illustrating DI in.NET Core


About the Reader For intermediate OO developers. About the Authors Mark Seemann is a programmer, software architect, and speaker who has been working with software since 1995, including six years with Microsoft. Steven van Deursen is a seasoned.NET developer and architect, and the author and maintainer of the Simple Injector DI library. Table of Contents

PART 1 Putting Dependency Injection on the map

  • The basics of Dependency Injection: What, why, and how
  • Writing tightly coupled code
  • Writing loosely coupled code

PART 2 Catalog

  • DI patterns
  • DI anti-patterns
  • Code smells

PART 3 Pure DI

  • Application composition
  • Object lifetime
  • Interception
  • Aspect-Oriented Programming by design
  • Tool-based Aspect-Oriented Programming

PART 4 DI Containers

  • DI Container introduction
  • The Autofac DI Container
  • The Simple Injector DI Container
  • The Microsoft.Extensions.DependencyInjection DI Container

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Dependency Injection Principles, Practices, and Patterns un PDF/ePUB en línea?
Sí, puedes acceder a Dependency Injection Principles, Practices, and Patterns de Mark Seemann, Steven van Deursen en formato PDF o ePUB, así como a otros libros populares de Informatik y Programmiersprachen. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Editorial
Manning
Año
2019
ISBN
9781638357100
Categoría
Informatik

Part 1. Putting Dependency Injection on the map

Dependency Injection (DI) is one of the most misunderstood concepts of object-oriented programming. The confusion is abundant and spans terminology, purpose, and mechanics. Should it be called Dependency Injection, Dependency Inversion, Inversion of Control, or even Third-Party Connect? Is the purpose of DI only to support unit testing, or is there a broader purpose? Is DI the same as Service Location? Do we need DI Containers to apply DI?
There are plenty of blog posts, magazine articles, conference presentations, and so on that discuss DI, but, unfortunately, many of them use conflicting terminology or give bad advice. This is true across the board, and even big and influential actors like Microsoft add to the confusion.
It doesn’t have to be this way. In this book, we present and use a consistent terminology. For the most part, we’ve adopted and clarified existing terminology defined by others, but, occasionally, we add a bit of terminology where none existed previously. This has helped us tremendously in evolving a specification of the scope or boundaries of DI.
One of the underlying reasons behind all the inconsistency and bad advice is that the boundaries of DI are quite blurry. Where does DI end, and where do other object-oriented concepts begin? We think that it’s impossible to draw a distinct line between DI and other aspects of writing good object-oriented code. To talk about DI, we have to pull in other concepts such as SOLID, Clean Code, and even Aspect-Oriented Programming. We don’t feel that we can credibly write about DI without also touching on some of these other topics.
The first part of the book helps you understand the place of DI in relation to other facets of software engineering — putting it on the map, so to speak. Chapter 1 gives you a quick tour of DI, covering its purpose, principles, and benefits, as well as providing an outline of the scope for the rest of the book. It’s focused on the big picture and doesn’t go into a lot of details. If you want to learn what DI is and why you should be interested in it, this is the place to start. This chapter assumes you have no prior knowledge of DI. Even if you already know about DI, you may still want to read it — it may turn out to be something other than what you expected.
Chapters 2 and 3, on the other hand, are completely reserved for one big example. This example is intended to give you a much more concrete feel for DI. To contrast DI with a more traditional style of programming, chapter 2 showcases a typical, tightly coupled implementation of a sample e-commerce application. Chapter 3 then subsequently reimplements it with DI.
In this part, we’ll discuss DI in general terms. This means we won’t use any so-called DI Container. It’s entirely possible to apply DI without using a DI Container. A DI Container is a helpful, but optional, tool. So parts 1, 2, and 3 more or less ignore DI Containers completely, and instead discuss DI in a container-agnostic way. Then, in part 4, we return to DI Containers to dissect three specific libraries.
Part 1 establishes the context for the rest of the book. It’s aimed at readers who don’t have any prior knowledge of DI, but experienced DI practitioners can also benefit from skimming the chapters to get a feeling for the terminology used throughout the book. By the end of part 1, you should have a firm grasp of the vocabulary and overall concepts, even if some of the concrete details are still a little fuzzy. That’s OK — the book becomes more concrete as you read on, so parts 2, 3, and 4 should answer the questions you’re likely to have after reading part 1.

1 The basics of Dependency Injection: What, why, and how

In this chapter
  • Dispelling common myths about Dependency Injection
  • Understanding the purpose of Dependency Injection
  • Evaluating the benefits of Dependency Injection
  • Knowing when to apply Dependency Injection
You may have heard that making a sauce béarnaise is difficult. Even among people who regularly cook, many have never attempted to make one. This is a shame, because the sauce is delicious. (It’s traditionally paired with steak, but it’s also an excellent accompaniment to white asparagus, poached eggs, and other dishes.) Some resort to substitutes like ready-made sauces or instant mixes, but these aren’t nearly as satisfying as the real thing.
A sauce béarnaise is an emulsified sauce made from egg yolk and butter, that’s flavored with tarragon, chervil, shallots, and vinegar. It contains no water. The biggest challenge to making it is that its preparation can fail. The sauce can curdle or separate, and, if either happens, you can’t resurrect it. It takes about 45 minutes to prepare, so a failed attempt means that you may not have time for a second try. On the other hand, any chef can prepare a sauce béarnaise. It’s part of their training and, as they’ll tell you, it’s not difficult.
You don’t have to be a professional cook to make sauce béarnaise. Anyone learning to make it will fail at least once, but after you get the hang of it, you’ll succeed every time. We think Dependency Injection (DI) is like sauce béarnaise. It’s assumed to be difficult, and, if you try to use it and fail, it’s likely there won’t be time for a second attempt.

Definition Dependency Injection is a set of software design principles and patterns that enables you to develop loosely coupled code.

Despite the fear, uncertainty, and doubt (FUD) surrounding DI, it’s as easy to learn as making a sauce béarnaise. You may make mistakes while you learn, but once you’ve mastered the technique, you’ll never again fail to apply it successfully.
Stack Overflow, the software development Q&A website, features an answer to the question, “How to explain Dependency Injection to a 5-year old?” The most highly rated answer, by John Munsch, provides a surprisingly accurate analogy targeted at the (imaginary) five-year-old inquisitor:1
1 See “How to explain Dependency Injection to a 5-year old?” by John Munsch et al. (2009), https://stackoverflow.com/questions/1638919/.
When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn’t want you to have. You might even be looking for something we don’t even have or which has expired.
What you should be doing is stating a need, “I need something to drink with lunch,” and then we will make sure you have something when you sit down to eat.
What this means in terms of object-oriented software development is this: collaborating classes (the five-year-old) should rely on infrastructure (the parents) to provide necessary services.

Note In DI terminology, we often talk about services and components. A service is typically an Abstraction, a definition for something that provides a service. An implementation of an Abstraction is often called a component a class that contains behavior. Because both service and component are such overloaded terms, throughout this book, you’ll typically see us use the terms “Abstraction” and “class” instead.

This chapter is fairly linear in structure. First, we introduce DI, including its purpose and benefits. Although we include examples, overall, this chapter has less code than any other chapter in the book. Before we introduce DI, we discuss the basic purpose of DI — maintainability. This is important because it’s easy to misunderstand DI if you aren’t properly prepared. Next, after an example (Hello DI!), we discuss benefits and scope, laying out a road map for the book. When you’re done with this chapter, you should be prep...

Índice