Dependency Injection (DI) is a software design pattern. Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.
Dependency Injection
reduces the hard-coded dependencies among your classes by injecting those
dependencies at run time instead of design time technically.
It is critical to take a step back to the basics of designing
an object-oriented application where a major facet of design is “loose
coupling.” This means that objects only have as many dependencies as needed to
do their jobs–and, the number of dependencies should be limited.
This article explains
how to implement Dependency Injection in C# and .NET code.
We have the following
ways to implement Dependency Injection.
1.
Constructor Injection
2.
Setter Injection
3.
Method Injection
Since DI is utilized to make code maintainable, it uses a pattern with a builder object to initialize objects and give the required dependencies to the object. As you can see, you can now “inject” a dependency from outside the class.
How Dependency Injection C# Works
To illustrate, if your Client class needs to use a Service class
component, the most you can do is make your Client aware of an IService
interface instead of a Service class. Through this execution, you get to change
the implementation of the Service class as many times as you like without
breaking the host code.
It is helpful to understand the Dependency
Inversion Principle, which gives us the guidelines for writing
loosely-coupled classes. Here is the definition:
Ø High-level modules
should not depend on low-level modules. Both should depend on abstractions.
Ø Abstractions should not
depend upon details. Details should depend upon abstractions.
How do you get two modules to depend on each other? Through Inversion
of control. This is the actual mechanism you can use to make higher-level
modules that depend on abstractions. You must invert the control to follow the
dependency inversion principle. As a result, your high-level modules are no
longer dependent on the lower-level concrete implementations.
Let’s dive a bit deeper into the three types of Dependency
Injections:
Constructor Injection in C#:
1.
This is a widely used way to implement DI.
2. Dependency Injection is done by supplying the
DEPENDENCY through the class’s constructor when creating the instance of that
class.
3.
Injected component can be used anywhere within the
class.
4.
Recommended to use when the injected dependency, you are using
across the class methods.
5. It addresses the most common scenario where a class requires one or more dependencies.
We can use the injection component anywhere within the class. It addresses the most common scenario where a class requires one or more dependencies. The following is an example:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace propertyinjuction
- {
- public interface text
- {
- void print();
- }
- class format : text
- {
- public void print()
- {
- Console.WriteLine(" here is text format");
- }
- }
- // constructor injection
- public class constructorinjection
- {
- private text _text;
- public constructorinjection(text t1)
- {
- this._text = t1;
- }
- public void print()
- {
- _text.print();
- }
- }
- class constructor
- {
- static void Main(string[] args)
- {
- constructorinjection cs = new constructorinjection(new format());
- cs.print();
- Console.ReadKey();
- }
- }
- }
By passing the services
that implemented the text interface the builder assembled the dependencies.
Property/Setter Injection:
1.
Recommended using when a class has optional
dependencies, or where the implementations may need to be swapped.
2.
Different logger implementations could be used in
this way.
3.
Does not require the creation of a new object or
modifying the existing one. Without changing the object state, it could work.
We use constructor injection, but there are some cases where I need a parameter-less constructor, so we need to use property injection. The following is an example:
- public interface INofificationAction
- {
- void ActOnNotification(string message);
- }
- class atul {
- INofificationAction task = null;
- public void notify(INofificationAction at ,string messages)
-
{
- this.task = at;
- task.ActOnNotification(messages);
-
}
- }
- class EventLogWriter : INofificationAction
- {
- public void ActOnNotification(string message)
- {
- // Write to event log here
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- //services srv = new services();
- //other oth = new other();
- //oth.run();
- //Console.WriteLine();
- EventLogWriter elw = new EventLogWriter();
- atul at = new atul();
- at.notify(elw, "to logg");
- Console.ReadKey();
- }
- }
You cannot control when
the dependency is set at all, it can be changed at any point in the object's
lifetime.
Method Injection in C#:
1. Inject the dependency into a single method and generally for the use of that method.
2.
It could be useful, where the whole class does not
need the dependency, only one method having that dependency.
3.
This is the way is rarely used.
The following is an example:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace propertyinjuction
- {
- public interface Iset
- {
- void print();
- }
- public class servic : Iset
- {
- public void print()
- {
- Console.WriteLine("print........");
- }
- }
- public class client
- {
- private Iset _set;
- public void run(Iset serv)
- {
- this._set = serv;
- Console.WriteLine("start");
- this._set.print();
- }
- }
- class method
- {
- public static void Main()
- {
- client cn = new client();
- cn.run(new servic());
- Console.ReadKey();
- }
- }
- }
Advantages of Dependency Injection
1.
Reduces class coupling
2.
Increases code reusability
3.
Improves code maintainability
4.
Make unit testing possible
DI Container
The recommended way to implement DI is, you should use DI
containers. If you compose an application without a DI CONTAINER, it is like a POOR
MAN’S DI
. If you want to implement DI within your ASP.NET
MVC application using DI container, please do refer Dependency Injection in ASP.NET MVC using Unity IoC
Container.
This article helps to
reduces class coupling, increase code reuse, improve code maintainability,
improve application testing and help to easily do unit testing. In this article
with code samples, we saw some use cases of dependency injection using C# and .NET.