Click below for Step by Step and Interview Q & A (dotnetinter) wrote,
Click below for Step by Step and Interview Q & A
dotnetinter

C# design pattern interview question: - DI vs IOC

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.


                              3rd image


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 Hollywood principle “Don’t call us we will call you”.  In Hollywood when artists used to give auditions the judges would say them “Don’t call us we will call you”.

The above approach makes code more flexible as the caller is not aware of the object methods and the object is not aware of caller program flow.

A word of caution here, do not conclude that IOC are implemented by only events.  You can delegate the control flow by callback delegates, observer pattern, events, DI (Dependency injection) and lot of other ways.

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.


                          4th image


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

ID

Tags: .net and c# training, c# design pattern interview question, c# interview questions, csharp interview questions, information technology questions
Subscribe

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments