Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[Tips] What is Dependency Injection, Dependency injection example in CSharp

Wednesday 29 March 2017
|
Read: Completed in minutes

[Tips] What is Dependency Injection, Dependency injection example in CSharp

Dependency injection is a design pattern that allows you to decouple your classes from their dependencies, such as other classes, interfaces, or frameworks. Dependency injection makes your code more modular, testable, and maintainable, as you can easily swap or mock the dependencies without changing the dependent class.

The basic idea of dependency injection is to pass the dependencies to the dependent class through a constructor, a property, or a method, rather than creating them inside the class. This way, the dependent class does not need to know how to create or access the dependencies, but only how to use them.

Dependency Injection in C#: A Simple Example

For example, suppose you have a class called EmailSender that sends emails using an external service called EmailService. Without dependency injection, you would create an instance of EmailService inside the EmailSender class, like this:

public class EmailSender
{
// Create an instance of EmailService
private EmailService emailService = new EmailService();

// Send an email using EmailService
public void SendEmail(string to, string subject, string body)
{
emailService.Send(to, subject, body);
}
}

However, this approach has some drawbacks. For instance, if you want to change the email service provider, you would have to modify the EmailSender class. Also, if you want to test the EmailSender class, you would have to deal with the real EmailService, which may be slow or unreliable.

With dependency injection, you would pass an instance of EmailService to the EmailSender class through a constructor parameter, like this:

public class EmailSender
{
// Declare a private field for EmailService
private EmailService emailService;

// Inject an instance of EmailService through the constructor
public EmailSender(EmailService emailService)
{
this.emailService = emailService;
}

// Send an email using EmailService
public void SendEmail(string to, string subject, string body)
{
emailService.Send(to, subject, body);
}
}

Now, the EmailSender class does not create or access the EmailService directly, but receives it as a dependency. This way, you can easily change or mock the EmailService without affecting the EmailSender class.

In conclusion, dependency injection is a useful technique that helps you write cleaner and more flexible code in C#. You can use various frameworks or libraries that support dependency injection in C#, such as Autofac, Ninject, or Unity.

Another example: 

The dependency injection pattern one of the most popular design paradigms today. It is process of removing dependency of object which creates the independent business objects. It is very useful for Test Driven Development.

Dependency Injection in C#: A Simple Example
This example show you how to write log file with C# dependency injections pattern

Take a look this example. First we need to create one employee class create a constructor objects, next we need to create ILogger interface with writeToLog method. Finally create two LoggerOne and LoggerTwo implement ILogger to modified writeToLog method.


What is Dependency Injection, Dependency injection example in CSharp

Code demo:

We have one Interface and three classes:
- Interface: ILogger.cs
- Three Classes: Employee, LoggerOne.cs, LoggerTwo.cs

Interface: ILogger.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjection
{
    public interface ILogger
    {
        void writeToLog(string text);
    }
}


Three Classes:


Employee.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjection
{
    public class Employee
    {
        public Employee(ILogger logger)
        {
            logger.writeToLog("New employee created");
        }    
    }
}

LoggerOne.cs implement from ILogger.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjection
{
    class LoggerOne : ILogger
    {
        public void writeToLog(string text)
        {
            Console.WriteLine(text);            
        }    
    }
}

LoggerTwo.cs implement from ILogger.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjection
{
    class LoggerTwo : ILogger
    {
        public void writeToLog(string text)
        {
            Console.WriteLine("*************** \n {0} \n ***************" +  text);
        }
    }
}

Main Program:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DependencyInjection
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employee1 = new Employee(new LoggerOne());
            Employee employee2 = new Employee(new LoggerTwo());
            Console.ReadLine();
        }
    }
}

And the output:

New employee created
*******************
New employee created
*******************

Thank you for reading this post. I hope you found it helpful and easy to follow. If you have any feedback or questions about Dependency Injection in C#: A Simple Example , please share them in the comments below. I would love to hear from you and discuss this topic further
✋✋✋✋  Webzone Tech Tips Zidane, all things tech tips web development  - I am Zidane, See you next time soon ✋✋✋✋


#CSharp #DependencyInjection #DesignPattern #Decoupling #Modularity #Testability #Maintainability #ConstructorInjection #Autofac #Ninject #Unity

🙇🏼 We Appreciate Your Comments and Suggestions - Webzone - all things Tech Tips web development 🙇🏼
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com