In this guide, you will explore Decimal Injection in C# along with its various types and illustrative instances.
What is Dependency Injection?
Dependency injection, commonly known as DI, stands as a well-recognized design pattern in various programming languages, including C#. This technique involves acquiring a class's dependencies externally instead of constructing them within the class itself. By promoting a decoupling of components, it enhances the adaptability, testability, and sustainability of the codebase.
Put differently, these specifications are passed to the object from an outside origin, typically via a constructor, setter method, or Interface, instead of the object generating its own dependencies or relying on a universal state. This approach allows for a more modular, testable, and sustainable programming style since objects can be easily interchanged or tested in isolation.
Utilizing a framework or container to manage the injection of dependencies is a common approach to implementing 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 refers to a form of dependency injection (DI) where a class is supplied with its dependencies through its constructor. This approach enhances testability and encapsulation by guaranteeing that all necessary dependencies are present when the class is instantiated.
Example:
Let's consider an instance to demonstrate dependency injection through constructors 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 illustrated in the following C# code snippet. The implementation involves the EmailService, which begins with an interface named IEmailServices that outlines the requirements for email services. Within the NotificationService class, constructor injection is exhibited by providing an instance of IEmailServices as an argument in its constructor. To inject the email service dependency into the NotificationService constructor, an EmailService instance is created and passed to it within the Main Method. Eventually, the injected dependency is utilized to invoke the NotifyUser method on notificationService, enabling the sending of an email notification containing the specified user email and message.
Property Injection
In C#, property injection is a form of dependency injection where a class obtains its dependencies through public properties. Unlike constructor injection, which passes dependencies through the constructor during object initialization, property injection allows specifying dependencies after the object has been created.
Example:
Let's consider an instance to demonstrate the utilization of dependency injection through 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 instance, the following code showcases the application of dependency injection through property injection. Initially, an interface named ILogger is employed to define the logging necessity, with the specific implementation being provided by ConsoleLogger. The external injection of the dependency is feasible due to MyDemoClass containing a Logger property of the ILogger type. Subsequently, within the Main Method, a ConsoleLogger object is allocated to the Logger property of a newly created MyDemoClass instance. Ultimately, the DoSomething method utilizes the injected logger to output the message "Do everything in love.." to the console.
Method Injection
Another form of Dependency Injection (DI) in C# is known as method injection, where dependencies are passed as arguments to a method. This approach offers a finer level of control over dependency injection compared to injecting dependencies at the class level, enabling them to be supplied to individual methods as required.
Example:
Let's consider a scenario to demonstrate the utilization of dependency injection through 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) using method injection is illustrated in the following C# code snippet. Initially, an ILogger interface is established to abstract the logging operations. Subsequently, the ConsoleLogger class is developed to adhere to this interface and handle message logging to the console. Within the MyDemoClass, the DoSomething method is enclosed, facilitating the injection of external dependencies through the inclusion of an ILogger object parameter. In the Main Method, a ConsoleLogger instance is instantiated and then supplied as an argument to the DoSomething method of MyDemoClass, showcasing the injection of dependencies into the class.