Dependency Inject
Dependency Inject
#dependenc
y-injection
Table of Contents
About 1
Remarks 2
Examples 2
Remarks 3
Examples 3
Web Api 3
MVC 4
ASP.NET Core 5
Examples 7
Constructor Injection 7
Examples 9
Examples 10
A Very Simple Example of Property Injection with C# with a Lazy-loaded Local Default 10
A Simple Example of Property Injection, setting the default via constructor injection 11
Credits 13
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: dependency-injection
It is an unofficial and free dependency-injection ebook created for educational purposes. All the
content is extracted from Stack Overflow Documentation, which is written by many hardworking
individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official dependency-
injection.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with dependency-
injection
Remarks
In object-oriented programming, objects often depend on other objects in order to do things.
Dependency Injection (DI) is giving an object the things that it depends on so that it doesn't have
to worry about getting them itself. That is, the dependencies are injected into the object. This is
most often done with constructor injection or property injection.
Dependency injection is a form of Inversion of Control (IoC). IoC is a broader term that describes
a pattern of software design.
In traditional procedural programming, the flow of control follows logically in steps. The control is in
the hands of the object or function performing operations. Step-by-step the program performs a
series of operations that it controls explicitly.
Instead of the object or function detailing every step, the flow of control can be inverted by making
the operations be performed by more generic and abstract objects - usually a framework that is
broader in scope.
Examples
What is a basic example of dependency injection?
class Dog {
public Dog() {
var food = new Food();
this.eat(food);
}
}
Here is the same class being injected with its dependency using constructor injection:
class Dog {
public Dog(Food food) {
this.eat(food);
}
}
https://riptutorial.com/ 2
Chapter 2: .NET - Pure DI examples
Remarks
An example of how to use dependency injection in .net without using a container. Based on
examples by Mark Seemann http://blog.ploeh.dk/
Examples
Web Api
https://riptutorial.com/ 3
public static class DependencyInjection
{
public static void WireUp()
{
var compositionRoot = new CompositionRoot();
System.Web.Http.GlobalConfiguration.Configuration.Services.Replace(typeof
(IHttpControllerActivator), compositionRoot);
}
}
MVC
https://riptutorial.com/ 4
// anything to clean up?
}
}
ASP.NET Core
in Startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
CompositionRoot.cs
public CompositionRoot()
{
// Create singletons
_singleton = new Singleton();
}
https://riptutorial.com/ 5
// dispose stuff
}
}
https://riptutorial.com/ 6
Chapter 3: Constructor Injection
Examples
Constructor Injection
public Example() {
myDatabase = new DatabaseThingie();
}
This class has one dependency called DatabaseThingie. Here in this example class Example is
responsible for creating its own dependencies, thereby violating Single Responsibility Principle.
Class has some primary responsibility + it is creating its won dependencies. If dependency
creation mechanism changes, Let say now the dependency take argument or Instead of
DatabaseThingie I want some other type. The class will change.
Here we are Injecting dependency from external source using Constructor Injection (Passing
dependency in constructor)
We don't care what type of dependency is injected, We just use it. The class won't change due to
https://riptutorial.com/ 7
this.
void testDoStuff() {
MockDatabase mockDatabase = new MockDatabase();
example.DoStuff();
mockDatabase.AssertGetDataWasCalled();
}
}
https://riptutorial.com/ 8
Chapter 4: Method injection
Examples
A Simple Example of Method Injection in c#
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var foo = new Dependency();
var bar = new ClassWithDependency();
Console.ReadLine();
}
}
https://riptutorial.com/ 9
Chapter 5: Property Injection
Examples
A Very Simple Example of Property Injection with C# with a Lazy-loaded Local
Default
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var foo = new ClassWithDependency();
foo.DoSomething();
foo.DoSomething();
Console.ReadLine();
}
https://riptutorial.com/ 10
{
get
{
if (_dependency == null) Dependency = new DefaultDependency();
return _dependency;
}
set { _dependency = value; }
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var dep = new DefaultDependency();
var foo = new ClassWithDependency(dep);
foo.DoSomething();
foo.DoSomething();
Console.ReadLine();
}
https://riptutorial.com/ 11
{
Console.WriteLine("Different behaviour");
}
}
https://riptutorial.com/ 12
Credits
S.
Chapters Contributors
No
.NET - Pure DI
2 tomliversidge
examples
https://riptutorial.com/ 13