In this article, you will learn about the Decimal Injection in C# with their types and examples.
What is Dependency Injection?
The dependency injection or DI is a popular design pattern in C# and other programming languages. It is a method where a class's dependencies are obtained outside rather than developed inside the class. It encourages loose coupling between components, improving the code's flexibility, testability, and maintainability.
In other words, such requirements are supplied to the object from an external source, usually through a constructor, setter method, or Interface, rather than the object creating its dependencies or depending on a global state. It enables more modular, testable, and maintainable programming because objects may be readily replaced or tested separately.
Using a framework or container to handle the injection of dependencies is a typical way to accomplish dependency injection in object-oriented programming.
Types of Dependency Injection in C#
In C#, there are three different kinds of dependency injections.
- Constructor Injection
- Property Injection
- Method Injection
Constructor Injection
In C#, constructor injection is a dependency injection (DI) in which a class receives dependencies through its constructor. Better testability and encapsulation are provided by this Method, which ensures that the class has all of its dependencies available at instantiation time.
Example:
Let us take an example to illustrate the dependency injection using constructor in C#.
using System;
//Interface that demonstrates dependency
public interface IEmailServices
{
void Sending_Email(string to, string subject, string body);
}
// Concrete implementation of the dependency
public class EmailService : IEmailServices
{
public void Sending_Email(string to, string subject, string body)
{
//code for sending email
Console.WriteLine($"Sending email to: {to} \nSubject: {subject} \nBody: {body}");
}
}
// Constructor injection makes the class dependent on the IEmailServices interface.
public class NotificationService
{
private readonly IEmailServices _email_Service;
// IEmailServices dependency accepted by the constructor.
public NotificationService(IEmailServices email_Service)
{
_email_Service = email_Service;
}
public void NotifyUser(string userEmail, string message)
{
// Send email notification using injected dependency
_email_Service.Sending_Email(userEmail, "Notification", message);
}
}
class Demo
{
static void Main(string[] args)
{
// Creating an instance of the dependency
IEmailServices email_Service = new EmailService();
//Utilizing constructor injection, inject the dependency into NotificationService.
NotificationService notificationService = new NotificationService(email_Service);
//Make use of the injected dependency by calling a NotificationService method.
notificationService.NotifyUser("example123@example.com", "This is a test notification of mail.");
}
}
Output:
Sending email to:[email protected]Subject: Notification
Body: This is a test notification of mail.
Explanation:
Constructor injection of dependency injection is demonstrated in this C# code. EmailService offers a practical implementation, starting with an IEmailServices interface that defines a contract for email services. NotificationService demonstrates constructor injection by passing an instance of IEmailServices as a parameter in its constructor. The email service dependency is injected into the NotificationService constructor by creating an instance of EmailService and passing it to it in the Main Method. Lastly, the injected dependency is used to execute the NotifyUser method on notificationService and send an email notification with the given user email and message.
Property Injection
In C#, property injection is another dependency injection (DI) in which a class receives dependencies via public properties. Dependencies can be specified after the object has been established via property injection, unlike constructor injection, which allows dependencies through the constructor.
Example:
Let us take an example to illustrate the dependency injection using property injection in C#.
using System;
//Interface representing the dependency
public interface ILogger
{
void Log(string message);
}
// Concrete implementation of the dependency
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
// Class-dependent via property injection on the ILogger interface
public class MyDemoClass
{
// Public property for injecting the dependency
public ILogger Logger { get; set; }
//Method utilizing the dependency
public void DoSomething()
{
Logger.Log("Do Everything in Love..");
}
}
class Demo
{
static void Main(string[] args)
{
MyDemoClass m = new MyDemoClass();
// Create a MyDemoClass instance.
ILogger l = new ConsoleLogger();
m.Logger = l;
m.DoSomething();
}
}
Output:
Do Everything in Love..
Explanation:
In this example, this code demonstrates dependency injection using property injection. To begin, an ILogger interface is used to describe a logging requirement, and ConsoleLogger is used to provide a specific implementation. It is possible to inject the dependency outside because MyDemoClass encapsulates a Logger property of type ILogger. A ConsoleLogger object is assigned to the Logger property of a MyDemoClass instance generated in the Main Method. Lastly, the message "Do everything in love.." is printed to the console by the DoSomething method, which uses the injected logger.
Method Injection
Another type of dependency injection (DI) in C# is called method injection , in which dependencies are sent as parameters to a method. Instead of injecting dependencies at the class level, this Method provides for more granular control over dependency injection by allowing them to be provided to specific methods as needed.
Example:
Let us take an example to illustrate the dependency injection using method injection in C#.
using System;
//Interface that demonstrates dependency
public interface ILogger
{
void Log(string message);
}
// Concrete implementation of the dependency
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
// The ILogger interface depends on the class.
public class MyDemoClass
{
//Method that takes ILogger as an injection parameter.
public void DoSomething(ILogger l)
{
l.Log("Do Everthying in Love...");
}
}
class Demo
{
static void Main(string[] args)
{
// Creating an instance of the dependency
ILogger l = new ConsoleLogger();
// Creating an instance of MyDemoClass
MyDemoClass m = new MyDemoClass();
// Use the injected ILogger dependency to call the MyDemoClass method.
m.DoSomething(l);
}
}
Output:
Do Everything in Love...
Explanation:
Dependency injection (DI) via method injection is demonstrated in this C# code. An ILogger interface is first defined to abstract logging functionality. After that, the ConsoleLogger implements this Interface to log messages to the console. MyDemoClass encapsulates the DoSomething method, which allows external dependencies to be injected by taking an ILogger object as a parameter. A ConsoleLogger object is created in the Main Method and passed as an argument to the MyDemoClass DoSomething method to demonstrate how dependencies are injected into the class.