Tuesday, December 27, 2022

Dependency Injection (DI)


The Dependency Injection pattern is a particular implementation of Inversion of Control. Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).



Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.



The advantages of using Dependency Injection pattern and Inversion of Control are the following:
  • Reduces class coupling
  • Increases code reusing
  • Improves code maintainability
  • Improves application testing

    The principle say that "High level module should not depend upon the low level module, both should depend on abstraction. Details should depends upon abstraction". 



    Basically, instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies in to the constructor or via property setters, and you make it somebody else's problem (an object further up the dependency graph, or a dependency injector that builds the dependency graph). A dependency as I'm using it here is any other object the current object needs to hold a reference to.
    One of the major advantages of dependency injection is that it can make testing lots easier. Suppose you have an object which in its constructor does something like:
    public SomeClass() {
        myObject = Factory.getObject();
    }
    
    This can be troublesome when all you want to do is run some unit tests on SomeClass, especially if myObject is something that does complex disk or network access. So now you're looking at mocking myObject but also somehow intercepting the factory call. Hard. Instead, pass the object in as an argument to the constructor. Now you've moved the problem elsewhere, but testing can become lots easier. Just make a dummy myObject and pass that in. The constructor would now look a bit like:
    public SomeClass (MyClass myObject) {
        this.myObject = myObject;
    }
    

No comments:

Post a Comment

ASP.NET Core

 Certainly! Here are 10 advanced .NET Core interview questions covering various topics: 1. **ASP.NET Core Middleware Pipeline**: Explain the...