O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dependency Injection in .NET Core 2.0

Book Description

Inject dependencies and write highly maintainable and flexible code using the new .NET Core DI Engine

About This Book

  • Identify when to use the constructors, parameters, setters, or Interface Injection, for best results
  • Build dependencies not only for MVC within .NET but also for other frontend tools such as Angular
  • Create specific components or services to cover discrete and separate pieces of functionality and call them when needed.

Who This Book Is For

C# and .NET developers who have no idea what DI is and would like to understand how to implement it in their applications.

What You Will Learn

  • Understand the concept of DI and its implications in modern software construction
  • Learn how DI is already implemented in today's frameworks.
  • Analyze how DI can be used with current software to improve maintainability and scalability.
  • Learn the use of DI in .NET Core
  • Get used to the possibilities that DI offers the ASP.NET Core developer in different scenarios.
  • Learn about good practices and refactoring legacy code.

In Detail

.NET Core provides more control than ever over web application architectures. A key point of this software architecture is that it's based on the use of Dependency Injection as a way to properly implement the Dependency Inversion principle proposed in the SOLID principles established by Robert C. Martin.

With the advent of .NET Core, things have become much simpler with Dependency Injection built into the system. This book aims to give you a profound insight into writing loosely-coupled code using the latest features available in .NET Core. It talks about constructors, parameter, setters, and interface injection, explaining in detail, with the help of examples, which type of injection to use in which situation. It will show you how to implement a class that creates other classes with associated dependencies, also called IoC containers, and then create dependencies for each MVC component of ASP.NET Core. You'll learn to distinguish between IoC containers, the use of Inversion of Control, and DI itself, since DI is just a way of implementing IoC via these containers. You'll also learn how to build dependencies for other frontend tool such as Angular. You will get to use the in-built services offered by .NET Core to create your own custom dependencies.

Towards the end, we'll talk about some patterns and anti-patterns for Dependency Injection along with some techniques to refactor legacy applications and inject dependencies.

Style and Approach

Filled with examples, this book will take you through various techniques for injecting dependencies into your applications with or without the use of frameworks.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

Table of Contents

  1. Preface
    1. What this book covers
    2. What you need for this book
    3. Who this book is for
    4. Conventions
    5. Reader feedback
    6. Customer support
      1. Downloading the example code
      2. Downloading the color images of this book
      3. Errata
      4. Piracy
      5. Questions
  2. The SOLID Principles of Software Design
    1. In the beginning
      1. .NET and .NET Core
        1. About .NET Core
        2. ASP.NET Core
        3. About the IDE used in this book
        4. Other foundational changes in .NET Core
    2. The SOLID principles
      1. The Single Responsibility Principle (SRP)
        1. The background of the Separation of Concerns (SoC)
        2. Well-known examples of Separation of Concerns
        3. A basic sample of Separation of Concerns
    3. Another sample
    4. The Open/Closed principle
    5. Back to our sample
    6. The Liskov Substitution principle
      1. Back to the code again
      2. Other implementations of LSP in .NET
    7. The Interface Segregation principle
    8. Another sample
    9. The Dependency Inversion principle
    10. The (more or less) canonical example
    11. Other ways to implement Dependency Inversion
    12. Summary
  3. Dependency Injection and IoC Containers
    1. The Dependency Principle in more detail
      1. Let's look at an example
    2. Aspects of Dependency Injection
      1. Object Composition
      2. Object Lifetime
      3. Interception
    3. Ways to implement DI
      1. Property Injection in action
      2. Method Injection in practice
        1. .NET event architecture as Model Injection
    4. DI containers
      1. Service locators
      2. DI Containers for .NET
        1. Using Unity Container
        2. Using Castle Windsor
        3. Using StructureMap
        4. Using Autofac
    5. Dependency Injection in other frameworks
      1. DI in Angular
      2. Our first demo
    6. Summary
  4. Introducing Dependency Injection in .NET Core 2.0
    1. The main characteristics of .NET Core
    2. The main advantages of .NET Core
      1. Installation of .NET Core in the IDE
      2. Installation path for .NET Core in Visual Studio 2015
      3. .NET Core in Visual Studio 2017
      4. Types of deployment
      5. Checking other dependencies in .NET Core
    3. Dependency Injection in .NET Core
      1. DI Architecture and Object's Lifetime
      2. The class ActivatorUtilities and other helpers
      3. The Microsoft.Extensions.DependencyInjection container
      4. Checking the object's lifetime
      5. Mapping interfaces to instance classes
      6. The concept of Scope Applied to services
      7. Other extensions with DI functionality
        1. A reflection on the structure of .NET Core
        2. LogLevels Severity
    4. Summary
  5. Dependency Injection in ASP.NET Core
    1. ASP.NET Core from the command-line tools
      1. Creating the minimum possible application
      2. Changing to ASP .NET Core
        1. Middleware
    2. The Startup class and Dependency Injection
      1. Code explanation
    3. The New ASP.NET servers
      1. Kestrel
      2. WebListener
      3. Dependency Inversion in the architecture - OWIN
    4. Analyzing the default template
      1. Configuration files
      2. The Entry Point
      3. The default Startup class
    5. Dependency Injection in ASP.NET Core
      1. Services provided by ASP.NET Core
      2. The relation of services available at startup
      3. Identifying Services in the Web Application template
        1. Using Dependency Injection in ASP.NET MVC Views
        2. Garbage Collection and Custom Services
      4. Using Custom Services through Dependency Injection
        1. Services and data management
      5. Using Dependency Injection inside Views
    6. Summary
  6. Object Composition
    1. Understanding object relationships
    2. Object Composition
      1. Types of Object Composition
        1. Composition
          1. Consider an example
          2. Contrasting features of Composition
          3. Why are subclasses inside Composition?
          4. Important notes
        2. Aggregation
          1. Consider an example
    3. Composition versus Aggregation
      1. Advantages and disadvantages
      2. Other important relationships
        1. Association
          1. Example
          2. Explanation of the preceding code
        2. Types of Association
          1. Reflexive Association
          2. Indirect Association
    4. Composition over Inheritance
      1. Inheritance
        1. Example on User class
        2. New User Type
          1. Problem which we come across
          2. The solution to the problem
    5. Role of Object Composition in Dependency Injection
      1. Composition Root
    6. Composing .NET Core 2.0 Console application
    7. Object Composition in ASP.NET Core MVC 2.0
    8. Summary
  7. Object Lifetime
    1. Manage the object life cycle
      1. Stack versus heap
      2. Managed and unmanaged resources
      3. Generations
      4. Object creation
        1. The Copy constructor
      5. Object destruction
        1. Finalize
        2. The IDisposable interface
        3. Consider an example
      6. Implementing the IDisposable Interface
        1. Step1 -  Basic structure of class
        2. Step2 - Defining a Dispose Overload method
        3. Step3 -Modifying the Dispose(bool) for Derived classes
        4. Step 4 - Handling duplicate Dispose calls
    2. Object lifetime management in .NET Core
      1. Object creation
        1. Designing the interfaces
        2. The Concrete class
        3. The Service class
        4. The controller
        5. View
        6. Startup ConfigureServices
      2. Object lifetimes
        1. Singleton
        2. Scoped
        3. Transient
        4. Instance
      3. Object disposal
      4. When to choose what?
      5. Relationship and dependencies among lifetimes
        1. Singleton depending on Scoped and Transient
        2. Scoped depending on Singleton and Transient
        3. Transient depending on Singleton and Scoped
    3. Summary
  8. Interception
    1. Introducing Interception
      1. The decorator
      2. Patterns and principles for Interception
      3. Benefits of the Decorator approach
      4. Problems of the Decorator approach
    2. Aspect-oriented programming
      1. Cross-cutting concerns
      2. Aspect
      3. Aspect characteristics
      4. Advantages
      5. Aspect attached locations
      6. Types of AOP
    3. Investigating Interception
      1. The Interception process
      2. Castle Windsor
      3. Demonstration for using the Castle Windsor
        1. Creating an Interceptor
        2. Attaching an Interceptor
    4. Intermediate Language (IL) Weaving
      1. IL Weaving process
        1. Creating an aspect
        2. Attaching the aspect
    5. Interception in ASP.NET Core
      1. Filters
        1. Global filter
        2. Attributes
      2. Middleware
        1. Registration
        2. Execution
        3. Ordering
    6. Summary
  9. Patterns - Dependency Injection
    1. Dependency Inversion Principle
      1. Problems
      2. Solution
      3. Inversion of Control (IoC)
    2. Patterns
      1. Constructor Injection pattern
        1. The problem
        2. The solution
        3. Curveball
        4. Injecting with .NET Core 2.0
        5. Implementation inside ASP.NET Core 2.0
          1. ControllerActivatorProvider.cs
        6. Importance of the Constructor Injection pattern
        7. Advantages of the Constructor Injection pattern
        8. Disadvantages of the Constructor Injection pattern
      2. Property Injection pattern
        1. Curveball
        2. Advantages of the Property Injection Pattern
        3. Disadvantages of the Property Injection Pattern
      3. Method Injection Pattern
        1. Curveball
        2. Injecting with .NET Core 2.0
        3. Implementation inside .NET Core 2.0
          1. MvcServiceCollectionExtensions.cs
      4. Ambient context
        1. Curveball
        2. Implementation inside .NET Core 2.0
        3. The advantages of the Ambient Context
        4. The disadvantages of the Ambient Context
    3. Summary
  10. Anti-Patterns and Misconceptions on Dependency Injection
    1. When does Dependency Injection become an anti-pattern?
    2. Anti-patterns
      1. Control Freak
        1. Problem
          1. Concrete Factory
          2. Abstract Factory
          3. Static Factory
        2. Solution
      2. Poor Man's DI
        1. The approach
        2. Problem
        3. Solution
      3. Bastard Injection
        1. Problem
        2. Solution
      4. Constrained Construction
        1. Problem
        2. Solution
      5. Service Locator
        1. Design
        2. Advantages
        3. Problem
          1. Code reusability
        4. Solution
          1. Refactoring steps
    3. Summary
  11. Dependency Injection in Other JavaScript Frameworks
    1. TypeScript
    2. Architectural changes
      1. Modules in TypeScript
      2. External modules
      3. Dependency Injection in TypeScript
    3. Angular
      1. AngularJS
        1. Examples using Visual Studio 2017
          1. Understanding the structure of AngularJS bootstrap
          2. Data access and Dependency Injection
        2. Summing up Dependency Injection features inside AngularJS
    4. Angular 2+
      1. Microsoft's TypeScript is the preferred language in Angular 2+ 
      2. Angular tools
        1. Working with Angular
          1. Editing the initial project
          2. The structure of the main module
      3. DI in Angular 4
        1. The concept of a provider
      4. Wrapping it up
    5. Summary
  12. Best Practices and Other Related Techniques
    1. Tightly coupled systems
      1. The problem
      2. The solution - refactoring with DI
        1. Interface extraction
    2. Layered architecture
      1. The problem - The concrete class reference again
        1. Misuse of business and Data Access Layer assemblies
      2. Best practice for layered architecture
        1. Managed Extensibility Framework (MEF)
        2. Layers and MEF implementation
          1. Introduction of IUser
          2. The IModuleRegistrar interface
          3. The ModuleRegistrar class
          4. The IModule interface
          5. The ModuleInit class
          6. The ModuleLoader class
          7. Executing the ModuleLoader.LoaderContainer() method from Web App
        3. What have we achieved with MEF?
          1. Layers are separated
          2. All classes inside layers are now internal
          3. No concrete class instantiation inside the UI Layer
          4. More layers can be added to the architecture
        4. Conclusion
    3. Summary