Dependency Injection Pattern in C# - Short Tutorial
Dependency Injection Pattern in C# - Short Tutorial
Become a member
C# Corner Login
Ask Question
10_DependencyInjection_Code.zip
Download Free .NET & JAVA Files API
This article will be a concise tutorial on Dependency Injection Pattern and other related topics: the
Dependency inversion principle (DIP), Inversion of control (IoC) principle, and Dependency
Injection Container (aka IoC container). While short, this tutorial will go into enough breadth and
depth to provide a solid overview of the topics. This article is well suited for those who need to
master basic concepts fast.
Topics covered in this tutorial are typically asked of a candidate interviewing for a Senior Software
Engineer (.NET) position.
This is a basic tutorial and does not go into all of the finest details. People learn best when
presented with knowledge in “concentric circles." In the first circle, they are taught the basis of
everything; in the second concentric circle, they go over what they learned in the previous circle
and extend that knowledge with more details; then, in the next circle, they do
something similar again, etc. This article is meant to be the first pass on the topic for an
interested reader.
Topics presented
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 1/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
The main problem this pattern aims to solve is how to create “loosely coupled” components. It
does that by separating the creation of components from their dependencies.
1. Client. The client is a component/class that wants to use services provided by another
component, called a Service.
2. Service-Interface. The service interface is an abstraction describing what kind of services
the Service component is providing.
3. Service. The Service component/class is providing services according to Service-Interface
description.
4. Injector. Is a component/class that is tasked with creating Client and Service components
and assembling them together.
The way it works is that the Client is dependent on Service-Interface IService. The client depends
on the IService interface, but has no dependency on the Service itself. Service implements the
IService interface and offers certain services that the Client needs. Injector creates both Client
and Service objects and assembles them together. We say that Injector “injects” Service into
Client.
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 2/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
2 void UsefulMethod();
3 }
5 void IService.UsefulMethod() {
7 Console.WriteLine("Service-UsefulMethod");
8 }
9 }
12 //Constructor Injection
13 _iService1 = injectedService;
14 }
17 _iService1?.UsefulMethod();
18 }
19 }
24 return c;
25 }
26 }
31 cli.UseService();
32 Console.ReadLine();
33 }
34 }
Often in literature [1] one can find mentioned different types of Dependency Injection, classified
based on the method of injecting Service into Client. I think that is an unimportant distinction,
since the effect is always the same. That is, reference to Service is being passed to Client, no
matter how. But, for completeness, let us explain it.
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 3/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
2 void UsefulMethod();
3 }
5 void IService.UsefulMethod() {
7 Console.WriteLine("Service-UsefulMethod");
8 }
9 }
12 //1.Constructor Injection
13 _iService1 = injectedService;
14 }
16 //2.Method Injection
17 _iService1 = injectedService;
18 }
20 //3.Property Injection
21 set {
22 _iService1 = value;
23 }
24 }
27 _iService1?.UsefulMethod();
28 }
29 }
35 //1.Constructor Injection
37 //2.Method Injection
38 C.InjectService(S);
39 //3.Property Injection
40 C.Service = S;
41 return C;
42 }
43 }
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 4/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
Let us emphasize the main component in this design pattern. It is the fact that Client is
completely ignorant of the type of Service injected. It just sees interface IService, and has no clue
what version of Service is being injected. Let us look at the following class diagram:
The Client has no knowledge of which service is being injected, whether if it is Service1, Service2,
or Service3. That is the desired result. We see that components/classes Client, Service1, Service2,
and Service3 are “loosely coupled."
The Client class is now more reusable and testable. One typical usage of this feature is that in the
production environment Client is injected with real service Service1, and in the test environment,
the Client is injected Service2, which is a mock service created just for testing.
Benefits of this pattern
This pattern is very similar to GoF book Strategy Pattern [2]. The class diagram is practically the
same. The difference is in intent: 1) Dependency injection is more like Structural Patten that has
the purpose to assemble loosely coupled components and once assembled they usually stay that
way during Client lifetime; while 2) Strategy pattern is a Behavior Pattern whose purpose is to
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 5/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
offer different algorithms to the problem. These are usually interchangeable during the Client
lifetime.
DIP is one of five design principles known under the acronym SOLID [3], promoted by Robert C.
Martin [5]. The DIP principle states:
1. High-level modules should not depend on low-level modules. Both should depend on the
abstraction.
2. Abstractions should not depend on details. Details should depend on abstractions.
My interpretation is:
While high-level principles talk about “abstraction," we need to translate that into terms in our
specific programming environment. In this case, we'll use C#/.NET. Abstractions in C# are realized
by interfaces and abstract classes. When talking about “details," the principle means “concrete
implementations."
So, basically, that means that DIP promotes the usage of the interfaces in C# and concrete
implementations (low-level modules) should depend on interfaces.
As you can see, some dependencies (arrows) have inverted directions, so that is where the name
“inversion” originated.
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 6/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
The goal of DIP is to create “loosely coupled” software modules. Traditionally, high-level modules
depend on low-level modules. DIP's goal is to make high-level modules independent of low-level
modules’ implementation details. DIP achieves that by introducing an “abstract layer” (in the form
of an interface) between them.
Dependency Injection Pattern (*) follows this principle, and is often referred to as closely related
to DIP realization. But, the DIP principle is a broader concept and has an influence on other
design patterns. For example, when applied to the factory design pattern or Singleton design
pattern, it suggests that those patterns should return a reference to an interface, not a reference
to an object.
In traditional programming, a custom code always has flow control and calls libraries to perform
tasks.
The IoC principle proposes that (sometimes) the flow of control should be given to libraries
(“framework”), which will call custom code to perform tasks.
The framework plays the role of the main program in controlling application activity. The main
control of the program is inverted, moved away from you to the framework. Inversion of control
is a key part of what makes a framework different from a library ([26]).
The IoC principle promotes the development and usage of reusable “software frameworks” that
implement common scenarios. Then, problem-specific custom code is written and made to work
together with the “framework” to solve a specific task.
While IoC principle is often mentioned in the context of Dependency Injection Pattern (*) which
follows it, it is a much broader concept than DIP. For example, an “UI framework” based on event
handlers/callback methods also follows IoC principle. See [26], [25], [8] for more explanation.
Dependency Injection Pattern (*) follows this principle, since the normal traditional approach is
for the Client to create a Service and establish dependency. Here, control is inverted. That is, the
creation of Service and the creation of dependency are delegated to the Injector, which in this
case is the “framework."
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 7/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
In the terminology of IoC principle (***), DI Container has the role of the “framework” so often
you will see it referred to as “DI framework." My opinion is that word “framework” is overused,
and this leads to confusion (you have ASP MVC framework, DI framework, Entity Framework, etc.).
Often in literature, this is referred to as “IoC Container." But, I think the IoC principle (***) is a
broader concept than the DI pattern (*). Here we take the reality of the DI pattern
implementation on a large scale. So, “DI Container” is a much better name, but the name “IoC
Container” is very popular and is used broadly to mean the same thing.
What is DI Container
Remember DI pattern (*) and the role of the Injector? So, DI Container is an advanced
module/library that serves as an Injector for many Services at the same time. It enables the
implementation of DI pattern on a large scale, with many advanced functions. DI Containers are a
very popular architectural mechanism and many popular frameworks such as ASP MVC plan for
and enable the integration of DI Containers.
The most popular DI Containers are Autofac [10], Unity [15], Ninject [16], Castle Windsor [17], etc.
DI Container functions
Register Mappings
You need to tell the DI Container mappings between abstraction (interfaces) to concrete
implementations (classes) so that it can properly inject proper types. Here you feed the container
with the basic info it needs to work.
You need to tell the container what scope and lifetime the object it creates will have.
You need to tell the container. For example, if you want it so that every time it resolves
dependency a new object will be created, or if you want a singleton pattern applied. A singleton
can be, for example, per process, per thread, or per “user-defined scope”. Also, you need to
specify the desired lifetime of your object. You can configure, for example, object lifetime per
process, or object lifetime to be per “user-defined scope." This means that the object will be
disposed of at the end of the scope that the user defines. The container can enforce all that;
it just needs to be precisely configured.
Resolve Method
Here the actual work of creating and assembling the required object/type are done. The container
creates an object of a specific type, resolves all the dependencies, and injects them into the
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 8/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
created object. This method works recursively into depth until all dependencies are resolved. DI
Container does the work of resolving dependencies using technologies like reflection and other
similar technologies.
DI Container: Autofac – Simple example
One of the most used DI Containers in C# world is Autofac [10]. We will show a simple example of
how it works.
3 public Service() {}
4 }
8 iService = injectedService;
9 }
10 }
16 TypeNameHandling = TypeNameHandling.All
17 };
20 }
22 // Register mappings
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 9/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
24 builder.RegisterType < Service > ().As < IService > (); //(1)
27 //Resolve object
30 Console.WriteLine(MySerialize(client)); //(6)
31 Console.ReadLine();
32 }
33 }
As you can see, Autofac has its own API that we need to follow. At (1) we registered the mapping
IService->Service. Then in (2) we registered the Client itself. At (3) we build the container, and it is
ready for use. At (4) we do resolution, and that is where the resolution of dependencies and
injection is done.
In order to verify that we got an object we wanted, we serialize it at (5) and print it out at (6).
If you look again at (*) and the terminology there, you will see that our class Client has the role of
“Client” from (*), cour lass Service has the role of “Service” from (*), and our object Container has
the role of “Injector” from (*).
A short note: this is a tutorial – a demo of a concept code. The manner in which we used DI
Container in the above example, explicitly requesting dependencies resolution on the top level,
makes it a bit resemble Service Locator Pattern [29]. The proper usage of DI Container is as a
framework, not to explicitly request resolution of dependencies.
DI Container: Autofac – Deep dependency example
Now we will show a more complicated example with a deep dependency tree.
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 10/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
1 public class C {
5 obj_is = injectIs;
6 obj_it = injectIT;
7 }
8 }
9 public interface IS {}
10 public class S: IS {
14 obj_iu = injectIU;
15 obj_iv = injectIV;
16 }
17 }
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 11/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
18 public interface IT {}
19 public class T: IT {
22 obj_iz = injectIZ;
23 }
24 }
25 public interface IU {}
26 public class U: IU {}
27 public interface IV {}
28 public class V: IV {
31 obj_ix = injectIX;
32 }
33 }
34 public interface IZ {}
35 public class Z: IZ {}
36 public interface IX {}
37 public class X: IX {}
43 TypeNameHandling = TypeNameHandling.All
44 };
46 return serialized;
47 }
49 // Register mappings
59 //Resolve object
62 Console.WriteLine(MySerialize(c));
63 Console.ReadLine();
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 12/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
64 }
65 }
As can be seen from the execution result, Autofac DI Container did its work again. For example,
class S is, in terms of the terminology of DI Pattern (*), at the same time “Client” and “Service”. It is
a “Service” for class C, and a “Client” for classes U and V. The Object Container plays the role of
the “Injector”, in the terminology of (*).
Another note: this is a tutorial – a demo of concept code. The manner in which we used DI
Container in the above example, explicitly requesting dependencies resolution on the top level,
makes it a bit resemble Service Locator Pattern [29]. The proper usage of DI Container is to use it
as a framework, and not to explicitly request resolution of dependencies.
DI Container: Autofac – Configuring Object Scope and Lifetime
If we look at the above example, one question occurs to us. If we have two objects of class C,
objects c1 and c2, that were generated by DI Container through resolution, are these objects
different or the same? And what about dependent objects, like objects of class T - let’s call them
t1 and t2 - are they all different or the same?
2 var c1 = Container.Resolve<C>();
3 var c2 = Container.Resolve<C>();
The answer is: it is configurable. But, since we didn’t configure that in the previous example, we
will get the default behavior. That is, every time a new object is created. In this case objects, c1
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 13/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
Typical options for configuring object scope and lifetime for DI Container Autofac ([11], [12]) are:
2. Single Instance
Also known as “singleton”. That is basically, “singleton per process”. Every time you request
resolution in the process, you will get the same instance of the object.
7. Thread Scope
This does not exist as a separate configuration option, but instead relies on #3 to create a
named scope in your thread method and implement it as an “Instance Per Lifetime Scope”
solution.
Here are some examples of how the configuration options listed above look in the code:
3 //explicit definition
13 }
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 14/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
18 }
22 }
29 //similar to 3.
We will not go into more detail or provide code samples because that would be too much for this
article.
DI Container – Integration with application frameworks
DI Containers are a very popular architectural mechanism and many application frameworks plan
for and enable integration with DI Containers.
For example, ASP.NET MVC framework is exposing the interface IDependencyResolver [13] that
the prospect DI Container needs to implement. An example of integration with Autofac looks like
this:
2 // Context:
7 // and Autofac.IComponentContext
9 // System.Web.Mvc.IDependencyResolver
13 // .SetResolver(System.Web.Mvc.IDependencyResolver resolver)
14 DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
So, the point is ASP.NET MVC framework provides a registration point for dependency resolver. If
you do not want to use DI, that is fine too. But, if you want to use DI in your ASP.NET MVC
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 15/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
application, you can register your DI Container of choice with the application framework as shown
above. Magically, DI resolution will start to work in your application.
For info on how to integrate the Autofac DI container with other applications, see [27]. This is
enough material for this tutorial article.
Conclusion
In this article, we focused on the Dependency Injection Pattern (DI) and its industrial application
Dependency Injection Container (aka IoC Container). We also explained related principles for
software design, the Dependency Inversion Principle (DIP) and Inversion of Control (IoC) principle.
We showed some sample code using Autofac container. Emphasize is on the reader’s ability to
understand and appreciate the practical usage of DI Container in modern applications.
DI Pattern and DI Container are mainstream technologies of Software Architecture today and are
here to stay.
In this tutorial, we gave a concise and brief overview of the material suitable for the reader that
needs to master concepts fast. Further reading on the topics is recommended. Some beginner’s
tutorials are [14], [18] – [23]. Serious literature is [9], [8], [26].
References
[1] https://en.wikipedia.org/wiki/Dependency_injection
[2] https://en.wikipedia.org/wiki/Strategy_pattern
[3] https://en.wikipedia.org/wiki/SOLID
[4] https://en.wikipedia.org/wiki/Dependency_inversion_principle
[5] https://en.wikipedia.org/wiki/Robert_C._Martin
[6] https://en.wikipedia.org/wiki/Inversion_of_control
[7] https://en.wikipedia.org/wiki/Service_locator_pattern
[8] https://martinfowler.com/articles/injection.html
[9] Mark Seemann, Steven van Deursen - Dependency Injection Principles, Practices, and
Patterns, Manning Publications, 2019
[10] https://autofac.org/
[11] https://autofac.readthedocs.io/en/latest/lifetime/index.html
[12] https://autofac.readthedocs.io/en/latest/lifetime/instance-scope.html
[13] https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.idependencyresolver?
view=aspnet-mvc-5.2
[14] https://www.codeproject.com/Articles/615139/An-Absolute-Beginners-Tutorial-on-
Dependency-Inver
[15] http://unitycontainer.org/articles/introduction.html
[16] http://www.ninject.org/
[17] http://www.castleproject.org/projects/windsor/
[18] https://www.codeproject.com/Articles/465173/Dependency-Inversion-Principle-IoC-
Container-and-D
[19] https://www.codeproject.com/Articles/542752/Dependency-Inversion-Principle-IoC-
Container-Depen
[20] https://www.codeproject.com/Articles/568157/Dependency-Inversion-Principle-IoC-
Container-and-3
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 16/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
[21] https://www.codeproject.com/Articles/579970/Dependency-Inversion-Principle-IoC-
Container-and-2
[22] https://www.codeproject.com/Articles/581430/Dependency-Inversion-Principle-IoC-
Container-and-4
[23] https://www.codeproject.com/Articles/538536/A-Curry-of-Dependency-Inversion-
Principle-DIP-Inve
[24] https://www.educative.io/edpresso/what-is-inversion-of-control
[25] https://www.theserverside.com/definition/inversion-of-control-IoC
[26] https://martinfowler.com/bliki/InversionOfControl.html
[27] https://autofac.readthedocs.io/en/latest/integration/index.html
[28] https://stackify.com/net-core-dependency-injection/
[29] https://en.wikipedia.org/wiki/Service_locator_pattern
OUR BOOKS
Mark Pelf
Mark Pelf is the pen name of a Software Engineer from Belgrade, Serbia.
My Blog
https://markpelf.com/
1432 3.4k
0 0
Type your comment here and press Enter Key (Minimum 10 characters)
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 17/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
FEATURED ARTICLES
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 18/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
TRENDING UP
CHALLENGE YOURSELF
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 19/20
8/5/22, 5:55 PM Dependency Injection Pattern In C# - Short Tutorial
GET CERTIFIED
Java Developer
KEEPSECURE
DUBAI
Safe
Deposit
locker
Rental UAE
UAE’s premier safe
deposit box rental facility
Open
About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ Partners
C# Tutorials Common Interview Questions Stories Consultants Ideas Certifications
©2022 C# Corner. All contents are copyright of their authors.
https://www.c-sharpcorner.com/article/dependency-injection-pattern-in-c-sharp-short-tutorial/ 20/20