The main goal of Inversion of control and Dependency Injection is to remove dependencies of an application. This makes the system more decoupled and maintainable.
IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC. IOC is a concept where the flow of application is inverted. So for example rather than the caller calling the method.
SomeObject.Call();
Will get replaced with an event based approach as shown below.
SomeObject.WhenEvent += Call();
In the above code the caller is exposing an event and when that event occurs he is taking action. It’s based on the principle “Don’t call us we will call you”.
DI provides objects that an object needs. So rather than the dependencies construct themselves they are injected by some external means. For instance let’s say we have the following below class “Customer” who uses a “Logger” class to log errors. So rather than creating the “Logger” from within the class, you can inject the same via a constructor as shown in the below code snippet.
The biggest benefit achieved by the above approach is “Decoupling”. You can now invoke the customer object and pass any kind of “Logger” object as shown in the below code.
Customer obj = new Customer(new EmailLogger());
Customer obj1 = new Customer(new EventViewerLogger());
So summarizing the differences.
Inversion of control: It’s a generic term and implemented in several ways (events, delegates etc).
Dependency injection: DI is a subtype of IOC and is implemented by constructor injection, setter injection or method injection.
No comments:
Post a Comment