Dependency Injection in .NET Core 2.0: Make use of constructors, parameters, setters, and interface injection to write reusable and loosely-coupled code
By Marino Posadas and Tadit Dash
()
About this ebook
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.
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.
.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 ApproachFilled with examples, this book will take you through various techniques for injecting dependencies into your applications with or without the use of frameworks.
Related to Dependency Injection in .NET Core 2.0
Related ebooks
Rust Cookbook Rating: 0 out of 5 stars0 ratingsPySide GUI Application Development - Second Edition Rating: 0 out of 5 stars0 ratingsBuilding Microservices with .NET Core: Develop skills in Reactive Microservices, database scaling, Azure Microservices, and more Rating: 0 out of 5 stars0 ratingsMetasploit Bootcamp: The fastest way to learn Metasploit Rating: 0 out of 5 stars0 ratingsExpert Android Programming Rating: 0 out of 5 stars0 ratingsLearning Windows Server Containers Rating: 0 out of 5 stars0 ratingsLearning Microsoft Cognitive Services - Second Edition: Leverage Machine Learning APIs to build smart applications Rating: 0 out of 5 stars0 ratingsLearn Vue.js 2.0 in 7 Days: Journey through Vue.js Rating: 0 out of 5 stars0 ratingsMicroservices with Azure Rating: 0 out of 5 stars0 ratingsFull Stack Development with JHipster: Build modern web applications and microservices with Spring and Angular Rating: 0 out of 5 stars0 ratingsHands-On Microservices with C# 8 and .NET Core 3: Refactor your monolith architecture into microservices using Azure, 3rd Edition Rating: 0 out of 5 stars0 ratings.NET Core 2.0 By Example: Learn to program in C# and .NET Core by building a series of practical, cross-platform projects Rating: 0 out of 5 stars0 ratingsLearn C# Programming: A guide to building a solid foundation in C# language for writing efficient programs Rating: 0 out of 5 stars0 ratingsAzure Serverless Computing Cookbook Rating: 0 out of 5 stars0 ratingsMastering JavaScript Functional Programming: Write clean, robust, and maintainable web and server code using functional JavaScript Rating: 0 out of 5 stars0 ratingsMySQL 8 for Big Data: Effective data processing with MySQL 8, Hadoop, NoSQL APIs, and other Big Data tools Rating: 0 out of 5 stars0 ratingsBuilding Web Apps with Spring 5 and Angular Rating: 0 out of 5 stars0 ratingsAndroid Wear Projects: Create smart Android Apps for Wearables Rating: 0 out of 5 stars0 ratingsASP.NET Core 2 and Angular 5: Full-Stack Web Development with .NET Core and Angular Rating: 4 out of 5 stars4/5MySQL 8 Administrator's Guide: Effective guide to administering high-performance MySQL 8 solutions Rating: 0 out of 5 stars0 ratingsLearning Azure Functions Rating: 0 out of 5 stars0 ratingsLearning Angular - Second Edition: A no-nonsense guide to building real-world apps with Angular 5 Rating: 0 out of 5 stars0 ratings
Programming For You
Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsExcel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Unreal Engine from Zero to Proficiency (Foundations): Unreal Engine from Zero to Proficiency, #1 Rating: 3 out of 5 stars3/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsLinux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Spies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5
Reviews for Dependency Injection in .NET Core 2.0
0 ratings0 reviews
Book preview
Dependency Injection in .NET Core 2.0 - Marino Posadas
Dependency Injection in .NET Core 2.0
Make use of constructors, parameters, setters, and interface injection to write reusable and loosely-coupled code
Marino Posadas
Tadit Dash
BIRMINGHAM - MUMBAI
Dependency Injection in .NET Core 2.0
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2017
Production reference: 1071117
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78712-130-0
www.packtpub.com
Credits
About the Authors
Marino Posadas is an independent senior trainer, writer, and consultant in Microsoft Technologies and Web Standards. He is a Microsoft MVP in C#, Visual Studio, and Development Technologies; an MCT, MCPD, MCTS, MCAD, and MCSD; and he was the former Director of Development in Spain and Portugal for Solid Quality Mentors.
Marino has published 15 books and more than 500 articles on development technologies in several magazines and online publications. The topics covered in his books range from Clipper and Visual Basic 5.0/ 6.0 to C # and .NET- safe programming, programming with Silverlight 2.0 and 4.0, and Web Standards.
His latest books are Mastering C# and .NET Framework, by Packt, and The Guide to Programming in HTML5, CSS3, and JavaScript with Visual Studio. He is also a speaker at Microsoft events, having lectured in Spain, Portugal, England, the US, Costa Rica, and Mexico.
His website also contains developer's resources and videos, in English and Spanish, interviewing representatives of the Microsoft and Web Standards development world.
You can follow him on Twitter at @MarinoPosadas.
I'd like to thank Dominic Pereira, Denim Pinto, Lawrence Veigas, and Tiksha Sarang from Packt for their continuous support and confidence while writing this book. Special thanks to some professionals and technology evangelists whose work inspired different parts of this book, in particular, Mark Russinowich, Scott Hanselman, Scott Hunter (the lesser
Scotts), and, of course, Robert Martin and Martin Fowler, pioneers in this work. Also, I would like to remember my MVP lead, Cristina González Herrero, for her continuous encouragement and help, and other people at Microsoft who have always supported my activities. My memories go here to Alfonso Rodríguez, David Carmona, David Salgado, and Leon Welicki. My appreciation also goes to my mates at Netmind for their support in this initiative from the beginning. I dedicate this book to my wife, Milagros, who makes everything possible.
Tadit Dash is a software engineer by profession. As a software engineer, he usually works for 8 to 9 hours daily. Besides his daily work, he contributes to both online and offline communities. He co-founded the first technical community in his state, named Microsoft Developers Community Odisha, which is devoted to spreading awareness of the newest trends in technology among developers. This community organizes events and workshops in orphanages, schools, and colleges.
He writes articles and blogs and creates demos and videos for fellow programmers. Answering questions on online forums and social channels are the activities he enjoys the most. Due to his exceptional contribution to the technical community, Microsoft has awarded him with the Microsoft Most Valuable Professional accolade since 2014. CodeProject has awarded him the CodeProject MVP accolade (the first from Odisha and three times in a row for the years 2014, 2015, and 2016). For his constant mentorship, IndiaMentor featured him as a Young Mentor on their site.
He was recognized by DZone and awarded the Most Valuable Blogger accolade. He was awarded the Star and Achiever accolade from his organization. Motivating students in his sessions is something he is popular for. He is a regular technical and motivational speaker. He has spoken at many local events organized by different communities. He was a featured speaker in DevTechDay Nepal.
I would like to dedicate this book to my grandfather, the late Mr. Ganeswar Tripathy.
My grandmother Santipriya Tripathy, father, Dr. Gobinda Chandra Dash, mother, Mrs. Sasmita Tripathy, and brother, Tworit Dash who made sure that I am high on energy (with healthy food) and confidence all the time during writing. My uncles, Mr. Anil Tripathy, Mr. Aswin Tripathy, and Mr. Amiya Tripathy who always guide me to shape the approach to my new challenges. Mrs. Sujata Tripathy, who takes cares of me like my mother and Mr. Debendra Rath, my uncle, who never misses an opportunity to discuss ideas to strengthen my thoughts so that I deliver the best.
My guide and mentor, Mr. Gaurav Kumar Aroraa (who is a Microsoft MVP and renowned author), encouraged me to take up the project, and constantly motivated me throughout the preparation. I am so grateful to the Packt team, especially Mr. Lawrence Veigas (Content Development Editor), and Miss. Tiksha Sarang who corrected me in every chapter. Thanks to Mr. Nirmal Hota (mobile guru of Odisha), who is like my big brother, for his consistent efforts in throwing me out of my comfort zone while patting my back. Miss. Prakreeti Prasanna, as a well wisher and best friend, always adds an x-factor to my activities. All my friends, family members, colleagues, and Google, of course, are the ingredients for the success of this book. Special thanks to my community members, Microsoft Developers Community, Odisha, for waiting to hear the surprise. Last, but not the least, Miss. Jayashree Satapathy, who, being a part of my life, has taken every care to make my writing schedule smooth.
About the Reviewer
Gaurav Aroraa has his M.Phil in computer science. He is a Microsoft MVP, lifetime member of the Computer Society of India (CSI), Advisory member of IndiaMentor, certified scrum trainer/coach, XEN for ITIL-F and APMG for PRINCE-F and PRINCE-P. He is an Open Source developer, contributor to TechNet Wiki, and the founder of Innatus Curo Software LLC. For over 19 years of his career, he has mentored thousands of students and industry professionals. You can tweet Gaurav on his twitter handle at @g_arora.
He has authored the following books:
Building Microservices in ASP.NET Core, Packt Publishing
Learn C# in 7 Days, Packt Publishing
SOLID Principles Succinctly, Syncfusion
ASP.NET WebHooks Succinctly, Syncfusion
To my wife, Shuby Arora, and my angel (daughter), Aarchi Arora, who permitted me to steal some time for this book from the time I was supposed to spend with them. To the entire Packt team, especially Prajakta, whose coordination and communication during the period was tremendous.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787121305.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Table of Contents
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
The SOLID Principles of Software Design
In the beginning
.NET and .NET Core
About .NET Core
ASP.NET Core
About the IDE used in this book
Other foundational changes in .NET Core
The SOLID principles
The Single Responsibility Principle (SRP)
The background of the Separation of Concerns (SoC)
Well-known examples of Separation of Concerns
A basic sample of Separation of Concerns
Another sample
The Open/Closed principle
Back to our sample
The Liskov Substitution principle
Back to the code again
Other implementations of LSP in .NET
The Interface Segregation principle
Another sample
The Dependency Inversion principle
The (more or less) canonical example
Other ways to implement Dependency Inversion
Summary
Dependency Injection and IoC Containers
The Dependency Principle in more detail
Let's look at an example
Aspects of Dependency Injection
Object Composition
Object Lifetime
Interception
Ways to implement DI
Property Injection in action
Method Injection in practice
.NET event architecture as Model Injection
DI containers
Service locators
DI Containers for .NET
Using Unity Container
Using Castle Windsor
Using StructureMap
Using Autofac
Dependency Injection in other frameworks
DI in Angular
Our first demo
Summary
Introducing Dependency Injection in .NET Core 2.0
The main characteristics of .NET Core
The main advantages of .NET Core
Installation of .NET Core in the IDE
Installation path for .NET Core in Visual Studio 2015
.NET Core in Visual Studio 2017
Types of deployment
Checking other dependencies in .NET Core
Dependency Injection in .NET Core
DI Architecture and Object's Lifetime
The class ActivatorUtilities and other helpers
The Microsoft.Extensions.DependencyInjection container
Checking the object's lifetime
Mapping interfaces to instance classes
The concept of Scope Applied to services
Other extensions with DI functionality
A reflection on the structure of .NET Core
LogLevels Severity
Summary
Dependency Injection in ASP.NET Core
ASP.NET Core from the command-line tools
Creating the minimum possible application
Changing to ASP .NET Core
Middleware
The Startup class and Dependency Injection
Code explanation
The New ASP.NET servers
Kestrel
WebListener
Dependency Inversion in the architecture - OWIN
Analyzing the default template
Configuration files
The Entry Point
The default Startup class
Dependency Injection in ASP.NET Core
Services provided by ASP.NET Core
The relation of services available at startup
Identifying Services in the Web Application template
Using Dependency Injection in ASP.NET MVC Views
Garbage Collection and Custom Services
Using Custom Services through Dependency Injection
Services and data management
Using Dependency Injection inside Views
Summary
Object Composition
Understanding object relationships
Object Composition
Types of Object Composition
Composition
Consider an example
Contrasting features of Composition
Why are subclasses inside Composition?
Important notes
Aggregation
Consider an example
Composition versus Aggregation
Advantages and disadvantages
Other important relationships
Association
Example
Explanation of the preceding code
Types of Association
Reflexive Association
Indirect Association
Composition over Inheritance
Inheritance
Example on User class
New User Type
Problem which we come across
The solution to the problem
Role of Object Composition in Dependency Injection
Composition Root
Composing .NET Core 2.0 Console application
Object Composition in ASP.NET Core MVC 2.0
Summary
Object Lifetime
Manage the object life cycle
Stack versus heap
Managed and unmanaged resources
Generations
Object creation
The Copy constructor
Object destruction
Finalize
The IDisposable interface
Consider an example
Implementing the IDisposable Interface
Step1 - Basic structure of class
Step2 - Defining a Dispose Overload method
Step3 -Modifying the Dispose(bool) for Derived classes
Step 4 - Handling duplicate Dispose calls
Object lifetime management in .NET Core
Object creation
Designing the interfaces
The Concrete class
The Service class
The controller
View
Startup ConfigureServices
Object lifetimes
Singleton
Scoped
Transient
Instance
Object disposal
When to choose what?
Relationship and dependencies among lifetimes
Singleton depending on Scoped and Transient
Scoped depending on Singleton and Transient
Transient depending on Singleton and Scoped
Summary
Interception
Introducing Interception
The decorator
Patterns and principles for Interception
Benefits of the Decorator approach
Problems of the Decorator approach
Aspect-oriented programming
Cross-cutting concerns
Aspect
Aspect characteristics
Advantages
Aspect attached locations
Types of AOP
Investigating Interception
The Interception process
Castle Windsor
Demonstration for using the Castle Windsor
Creating an Interceptor
Attaching an Interceptor
Intermediate Language (IL) Weaving
IL Weaving process
Creating an aspect
Attaching the aspect
Interception in ASP.NET Core
Filters
Global filter
Attributes
Middleware
Registration
Execution
Ordering
Summary
Patterns - Dependency Injection
Dependency Inversion Principle
Problems
Solution
Inversion of Control (IoC)
Patterns
Constructor Injection pattern
The problem
The solution
Curveball
Injecting with .NET Core 2.0
Implementation inside ASP.NET Core 2.0
ControllerActivatorProvider.cs
Importance of the Constructor Injection pattern
Advantages of the Constructor Injection pattern
Disadvantages of the Constructor Injection pattern
Property Injection pattern
Curveball
Advantages of the Property Injection Pattern
Disadvantages of the Property Injection Pattern
Method Injection Pattern
Curveball
Injecting with .NET Core 2.0
Implementation inside .NET Core 2.0
MvcServiceCollectionExtensions.cs
Ambient context
Curveball
Implementation inside .NET Core 2.0
The advantages of the Ambient Context
The disadvantages of the Ambient Context
Summary
Anti-Patterns and Misconceptions on Dependency Injection
When does Dependency Injection become an anti-pattern?
Anti-patterns
Control Freak
Problem
Concrete Factory
Abstract Factory
Static Factory
Solution
Poor Man's DI
The approach
Problem
Solution
Bastard Injection
Problem
Solution
Constrained Construction
Problem
Solution
Service Locator
Design
Advantages
Problem
Code reusability
Solution
Refactoring steps
Summary
Dependency Injection in Other JavaScript Frameworks
TypeScript
Architectural changes
Modules in TypeScript
External modules
Dependency Injection in TypeScript
Angular
AngularJS
Examples using Visual Studio 2017
Understanding the structure of AngularJS bootstrap
Data access and Dependency Injection
Summing up Dependency Injection features inside AngularJS
Angular 2+
Microsoft's TypeScript is the preferred language in Angular 2+
Angular tools
Working with Angular
Editing the initial project
The structure of the main module
DI in Angular 4
The concept of a provider
Wrapping it up
Summary
Best Practices and Other Related Techniques
Tightly coupled systems
The problem
The solution - refactoring with DI
Interface extraction
Layered architecture
The problem - The concrete class reference again
Misuse of business and Data Access Layer assemblies
Best practice for layered architecture
Managed Extensibility Framework (MEF)
Layers and MEF implementation
Introduction of IUser
The IModuleRegistrar interface
The ModuleRegistrar class
The IModule interface
The ModuleInit class
The ModuleLoader class
Executing the ModuleLoader.LoaderContainer() method from Web App
What have we achieved with MEF?
Layers are separated
All classes inside layers are now internal
No concrete class instantiation inside the UI Layer
More layers can be added to the architecture
Conclusion
Summary
Preface
This book is an approach to the implementation of Dependency Injection techniques across the new .NET Core 2.0 version. The designers of .NET Core implemented plenty of functionalities related to good practices and have followed the principles stated by Robert C. Martin (the SOLID principles) in distinct areas of this version.
The purpose of this work is to go through those well-stated principles and identify and show through examples how they're implemented, and how they can be used by the programmer.
What this book covers
Chapter 1, The SOLID Principles of Software Design, introduces you to the five SOLID principles and how they are found or can be easily implemented in .NET Core 2.0.
Chapter 2, Dependency Injection and IoC Containers, gives you exposure to how Dependency Injection should be used either by itself or with the help of third-party containers.
Chapter 3, Introducing Dependency Injection in .NET Core 2.0, reviews the real implementation of DI inside .NET Core 2.0 from the point of view of Console applications.
Chapter 4, Dependency Injection in ASP.NET Core, provides a more detailed study of the implementation of DI techniques inside web applications that use ASP.NET Core 2.0, full of samples.
Chapter 5, Object Composition, takes you through all the hidden principles behind the concept of object composition and how it is applied in .NET Core 2.0 and ASP.NET Core MVC 2.0, forming a pillar of DI.
Chapter 6, Object Lifetime, the next DI pillar provides a deep dive into lifestyles maintained and typical management strategies, by the objects with DI in place, which enables better decision making with optimized configurations.
Chapter 7, Interception, the last pillar of DI ecosystem, provides techniques to intercept calls and insert code dynamically into the pipeline. This chapter also deals with interception's application in .NET Core 2.0 and ASP.NET Core 2.0 with proper illustrations.
Chapter 8, Patterns – Dependency Injection, walks you through the D of SOLID and all the important techniques to apply DI in applications with .NET Core 2.0.
Chapter 9, Anti-Patterns and Misconceptions on Dependency Injection, deals with the common bad usage of DI patterns and scenarios to avoid while coding, in order to get a good outcome from DI in the application.
Chapter 10, Dependency Injection in Other JavaScript Frameworks, teaches you about Dependency Injection techniques using other popular frameworks, such as Angular.
Chapter 11, Best Practices and Other Related Techniques, covers the well-proven coding, architectural, and refactoring practices that you should adopt while applying DI in your current and legacy applications.
What you need for this book
You will need Visual Studio 2017 Community Edition, the Chrome Navigator, and IIS (Internet Information Server Express) to successfully test and execute all code files.
Who this book is for
This book is for C# and .NET developers who have no idea what DI (Dependency Injection) is and would like to understand how to implement it in their applications.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: For this new requirement, we can create a new and overloaded the ReadData() method that receives an extra argument.
A block of code is set as follows:
public Student(int id, string name, DateTime dob)
{
Id = id;
Name = name;
Dob = dob;
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
static void Main(string[] args)
{
Packt packt = new Packt
{
Name = Packt Publications
,
OfficialFacebookLink = https://www.facebook.com/PacktPub/
,
TotalBooksPublished = 5000
};
packt.PrintPacktInfo();
Console.ReadKey();
}
Any command-line input or output is written as follows:
npm install -g json
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Double-click on Add ArcGIS Server.
Warnings or important notes appear like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book 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 files e-mailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Dependency-Injection-in-.NET-Core-2.0. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/DependencyInjectioninNETCore20_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
The SOLID Principles of Software Design
This book focuses on techniques related to Dependency Injection and the way those techniques are implemented by default and can be extended by the programmer in .NET Core--the first version of .NET that executes on every platform.
It works on Windows, macOS, and Linux distro on the desktop, and the idea can even be extended to the mobile world covering the Apple, Android, and Tizen (Samsung) operating systems.
This is, with no doubt, the most ambitious project from Microsoft in its search for a universal coverage of programming technologies and tools, and it can be considered a natural step after the initial UWP (Universal Windows Platform) project that allows building applications for any device supporting Windows, from IoT devices to the desktop, XBOX, or HoloLens.
So, in this chapter we'll start with a quick review of the main architectural components of .NET Core and its derivative frameworks (such as ASP.NET Core), to be followed with the foundations on which Dependency Injection techniques are based, as part of the SOLID principles, stated by Robert C. Martin (Uncle Bob) in 2000. (See Wikipedia: https://en.wikipedia.org/wiki/SOLID_(object-oriented_design).)
Therefore, we'll revise those five SOLID principles, explaining their purpose and advantages, together with some basic implementations of each one of them in the C# language using Console applications coded in .NET Core. In all we'll see an explanation of each principle and its coverage:
Separation of concerns (clearly implemented in the core infrastructure of .NET Core and also from the initial configuration of pipelines and middleware in ASP.NET Core)
Open/Closed (already implemented in classic .NET Framework since version 3.0 and also present here)
Liskov Substitution Principle (available in two ways--in a classic manner through the support of typecasting, and through the use of generics)
Interface segregation: Explanation of Interface segregation and its advantages
Dependency Inversion: Explanation of the principle, its derivatives, and the concept of IoC containers
In the beginning
The evolution of programming techniques is, somehow, related to language evolution. Once the initial (and, in some ways, chaotic) times had passed, the universality of computing became clear, and the need for good patterns and languages capable of affording large projects turned out to be evident.
The 70s marked the start of the adoption of other paradigms, such as procedural programming, and later on, object-oriented programming (OOP), proposed by Ole-Johan Dahl and Kristen Nygaard with the Simula language, when they both worked at the Norwegian Computing Center. They were given the Turing Award for these achievements, among other recognitions.
A few years later (around 1979), Bjarne Stroustrup created C with Classes, the prototype of what C++ is today because he found valuable aspects in the Simula language, but he thought that it was too slow for practical purposes, being the first OOP language that was universally adopted.
C++ originally had imperative features and object-oriented and generic ones, while also providing the ability to program for low-level memory manipulation. While it's true that it has become a de facto standard for building critical systems and applications, for many people it was not adequate for LOB (Line of Business) applications.
Years later, Java and the .NET platforms proposed a much easier and affordable solution for many programmers while still moving within the ordered space that object-oriented programming languages promote.
So, OOP was adopted, and so far no other important programming paradigm has replaced these ideas. Certainly, there are other approaches, such as functional programming, but even the most significant representative of this tendency, JavaScript, is becoming more object-oriented in the latest versions (ECMAScript 2015).
.NET and .NET Core
.NET has been revamped lately in order to achieve the goal that Microsoft has pursued since Satya Nadella arrived in the company--"Any Developer, Any App, Any Platforms.".
According to Principal Manager Scott Hunter, the company now presents a set of unified application models that can be summarized in the following screenshot:
Source: http://www.hanselman.com/blog/AnUpdateOnASPNETCore10RC2.aspx
As you see, the situation now is quite promising for a .NET Developer. The screenshot shows a Common Infrastructure (compilers, languages, and runtime components), powered by Roselyn services and other features. All those integrate with the IDEs that support these projects, now including Visual Studio for Mac.
On top of that lies a .NET Standard Library, which has points in common that allow us to share code along the three different frameworks--the classic .NET Framework (in version 4.6.2, at the time of writing this), .NET Core (now in version 2.0), and Xamarin, which allows building applications for any type of mobile target--Android, iOS, Windows Phone, and Tizen (Samsung).
About .NET Core
.NET Core is the new version of .NET presented officially in the summer of 2016, and updated to version 1.1 in the November Connect() event the same year. It's defined as a cross-platform, open source, cloud-ready and modular .NET platform for creating modern web apps, microservices, libraries, and console applications that run everywhere (Windows, Linux, and MacOS).
It can be deployed along with the application itself, minimizing installation issues.
Prior to its publication, Microsoft decided to restart the numbering, reinforcing the idea that this is a totally new concept with respect to classical versions, as a better way to avoid ambiguities.
MSDN architect Cesar de la Torre defines in his blog very precisely the goals and structure of .NET Core--unlike the traditional .NET Framework, which is a single package installation, system-wide, and Windows-only runtime environment, .NET Core is about decoupling .NET from Windows, allowing it to run in non-Windows environments without having to install a giant 400 Mb set of binaries (versus just the footprint of the components you need from .NET Core) plus the ability to deploy applications accompanying the framework itself, supporting side-by-side execution of different versions of the framework.
A very interesting part of its architecture and deployment infrastructure, as mentioned in the same source, is that instead of being part of the operating system, .NET Core is composed of NuGet packages and is either compiled directly into an application or put into a folder inside the application. This means applications can carry .NET Core within and thus are completely side by side on the machine.
I, personally, think this is absolutely crucial for the project to be successful. No side-effects, no component installation in the target machine, and no dependencies. (As you'll see throughout this book this avoiding of dependencies is totally