A One-Stop Solution Guide to Understand C# Dependency Injection

C# has evolved to accommodate new workloads and changing program design methodologies. It is an object-oriented and component-oriented language. Components can be created and used in C# using built-in language constructs. Classes frequently require class references. A Company instance may, for example, require an Employee class reference. In this case, the Company class requires an instance of the Employee class to function effectively.

You will cover the basics of C# Dependency Injection in this tutorial. Using the examples in this tutorial, you will learn how to implement C# Dependency Injection.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

What Is C# Dependency Injection?

Dependency Injection is a design pattern that allows for loosely linked applications. The purpose of Dependency Injection is to make code more manageable. Dependency injection is an excellent technique for reducing inter-dependency between software components. You can also better handle future updates and other complexity in our product thanks to Dependency Injection. 

Now you will explore various ways to implement C# Dependency Injection.

Ways to Implement C# Dependency Injection

C#Dependency-injection-ways-img1.

There are various ways to implement C# Dependency Injection:

  1. Constructor Dependency Injection
  2. Property Dependency Injection
  3. Method Dependency Injection

Now, you will explore them in detail, and get started with Constructor Injection.

Constructor Dependency Injection

In most cases, there is only one parameterized Constructor in the Constructor injection. In a Constructor dependency, there is no default Constructor to use. During the object creation process, you must pass the specified value. You can utilize the injection component wherever in the class, which is quite convenient.

Now, you will implement constructor dependency injection using code.

Code:

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Text;  

using System.Threading.Tasks;  

namespace propertyinjection  

{  

    public interface text  

    {

        void print();

    }

    class format : text

    {

        public void print()

        {

            Console.WriteLine("Welcome to Simplilearn");

        }      

    }

    // 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();          

        }

    }

}

C#Dependency-injection-Constructor-img3.

Now you will look at property Dependency Injection.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Property Dependency Injection

When you require a Constructor with fewer parameters, you often utilize a property. It is possible that it will work without affecting the state of the item.

Now, you will implement property dependency injection using code.

Code:

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Text;  

using System.Threading.Tasks;

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)

       {

           Console.WriteLine("Hi i am vaibhav");

       }

   }

   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();

       }

   }

C#-Dependency-injection-Property-img3

At last, you will explore Method Dependency Injection.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Method Dependency Injection

When using method injection, you only need to send the dependency into the method. You do not employ Constructor injection because doing so would result in the creation of a dependent object every time a class is instantiated in your application.

Now, you will implement method dependency injection using code.

Code:

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("Like, Share, And Subscribe!!!");          

        }      

    }

    public class client

    {

        private Iset _Iset;

        public void run(Iset serv)

        {  

            this._Iset = serv;

            Console.WriteLine("Welcome to Simplilearn");

            this._Iset.print();

        }      

    }

    class method

    {

        public static void Main()

        {

            client cn = new client();

            cn.run(new servic());

            Console.ReadKey();        

        }

    }

}

C#-Dependency-injection-Method-img3

Dependency Injection helps in Reducing class coupling. It increases the reusability of code. The Dependency Injection helps to improve code maintainability. Dependency Injection makes it feasible to conduct unit testing.

This is all for this session, next you can learn about C# Interfaces.

Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

Next Steps

"C# Interfaces" might be the next thing you want to learn about. A class blueprint is called an Interface in C#, and it looks like one. However, just like with abstract classes, any methods in an interface are abstract methods. You can say that, for example, it doesn't have a method body.

You've come to the perfect site if you want to learn more about software development and maybe work in it. Simplilearn’s Full Stack Developer - MERN Stack classes cover the fundamentals of data structures and algorithms as well as advanced ideas such as Competitive Programming. You will learn about data structures such as trees, graphs, and queues as a software developer.

If you have any comments or questions regarding this "C# Dependency Injection" tutorial, feel free to leave them in the comment box below. Our skilled team is available 24 hours a day and will swiftly react to your inquiries.

About the Author

Vaibhav KhandelwalVaibhav Khandelwal

Vaibhav Khandelwal is a proactive tech geek who's always on the edge of learning new technologies. He is well versed in competitive programming and possesses sound knowledge of web development. He likes to read fictional and sci-fi novels and likes to play strategy games like chess

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.