Before starting with Function Injection, let us recall what we have learned in our last session.
Dependency Injection is a kind of architectural style that talks about loose coupling among program components. We know that there are many advantages of loose coupling and it is very necessary to implement it in applications.
In this lesson, we will implement the Function Injection pattern. The concept is that there will be one service class and one client class. They want to talk with each other, now if we directly call the method of one class from another class then there will be a tight dependency between them. If we want to change one then the other will be affected. So, the solution is to place one interface between them and they will talk via an interface. The following diagram represents our concept.
In the picture, we see that the service is being consumed via an interface so there is no direct relation between the Service class and the Consumer class. Now, we will implement the above example in a console application. Have a look at the following code.
Let's understand with the help of a program.
using System; namespace ConsoleApp { public interface IServiceInterface { void Start(); } public class ServiceClass : IServiceInterface { public void Start() { Console.WriteLine("Service Started..."); } } public class ServiceConsumer { private IServiceInterface _service; public void Start(IServiceInterface s) { this._service = s; Console.WriteLine("Service Called..."); this._service.Start(); } } class Program { static void Main(string[] args) { //Create object of Client class ServiceConsumer client = new ServiceConsumer(); //Call to Start method with proper object. client.Start(new ServiceClass()); Console.ReadLine(); } } }
Let's try to understand the code above. This is one example of Dependency Injection using the Method Injection technique. The main part to understand of the above example is the Start() function within the ServiceConsumer class. This function is taking an argument of the IServiceInterface and it's calling the appropriate method by calling the Start() function.
The following are few points about method injection:
- Through the method, we are sending a specific object of the interface, so that it's called method injection.
- It could be useful in those scenarios where an entire class does not need the dependency. Just one method needs the dependency.
- It is one of the common types of Dependency Injection.
Output of the Method Injection approach |
Summary:
So, Guys, this is all about Function Injection.I Hope in this post covered all the points about Function/Method Injection which will be helpful to understand the concept Dependency Injection in C#.
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.