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.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

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.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

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.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

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 Software Development courses are co-taught by Caltech CTME and IIT-Kanpur. These 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

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

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