Skip to main content

SOLID Principle - Dependency Inversion Principle (DIP)

The SOLID Principles are the design principles that enable us to manage several software design problems. These principles provide us with ways to move from tightly coupled code to loosely coupled and encapsulated real business needs properly. Also readable, adaptable, and scalable code.

The SOLID Principles guide developers as they write readable, adaptable, and scalable code or design an application.

The SOLID Principles can be applied to any OOP program.

The SOLID Principles were developed by computer science instructor and author Robert C. Martin. Now, SOLID principles have also been adopted in both agile development and adaptive software development.

The 5 principles of SOLID are:

SOLID Principle: (5) Dependency Inversion Principle (DIP)

The Dependency Inversion Principle (DIP) is one of the SOLID principles of object-oriented design. The reason (DIP) is important is because it ensures the OO-principle "loosely coupled design".

The Dependency Inversion Principle (DIP) states that

Rule 1: The ‘High level’ modules or classes should not depend on ‘Low level’ modules or classes. Both should depend upon Abstractions.

Rule 2: Abstractions should not depend upon details. Details should depend upon abstractions (implementation of interface).


Abstractions means - we must create either an Interface or an Abstract class. So, we cannot create an instance of it.

To understand the Dependency Inversion Principle (DIP), first, we need to understand the concepts of High-level and Low-level modules.

High-level modules are modules that contain the main logic of the application, while Low-level modules are modules that provide supporting functionality.  

In the below example, we have two main classes DatabaseService and Logger:

First-class - DatabaseService is a low-level module that provides database access.

Second class - Logger is a high-level module that logs data.

Traditionally, Low-level modules depend on High-level modules, as the high-level modules call the low-level modules to perform their required functionality. However, this creates a tight coupling between the two modules. Therefore, it’s difficult to change one module without affecting the other.

The Dependency Inversion Principle solves this problem by introducing an abstraction layer between the high-level and low-level modules.

Points to remember when developing real-time applications - always keep High-level and Low-level modules as loosely coupled as possible. The class should be dependent on abstractions. It will allow your application to evolve more securely and stable.

In other words, the Dependency Inversion Principle (DIP) promotes the decoupling of software modules.

C# Dependency Inversion Principle (SIP) Example

The following example violates the dependency inversion principle (DIP):

namespace DIP;

public class DatabaseService

{

    public void Save(string message)

    {

        Console.WriteLine("Save the message into the database");

    }

}

public class Logger

{

    private readonly DatabaseService _databaseService;

 

    public Logger(DatabaseService databaseService)

    {

        _databaseService = databaseService;

    }

    public void Log(string message)

    {

        _databaseService.Save(message);

    }

}

 

public class Program

{

    public static void Main(string[] args)

    {

        var logger = new Logger(new DatabaseService());

        logger.Log("Hello");

    }

}

 

In this example, we have two main classes DatabaseService and Logger:

The DatabaseService is a low-level module that provides database access.

The Logger is a high-level module that logs data.

The Logger class depends on the DatabaseService class directly. In other words, the high-level module (Logger) depends on the low-level module (DatabaseService).

 

Rather than having the Logger class depend on the DatabaseService class, we can introduce an interface called IDataService that both classes depend on:

namespace DIP;

public interface IDataService

{

    public void Save(string message);

}

public class DatabaseService: IDataService

{

    public void Save(string message)

    {

        Console.WriteLine("Save the message into the database");

    }

}

 

public class Logger

{

    private readonly IDataService _dataService;

 

    public Logger(IDataService dataService)

    {

        _dataService = dataService;

    }

 

    public void Log(string message)

    {

        _dataService.Save(message);

    }

}

 

public class Program

{

    public static void Main(string[] args)

    {

        var logger = new Logger(new DatabaseService());

        logger.Log("Hello");

    }

} 


In this example:

First, define the IDataAccess interface that has the Save() method:

public interface IDataService

{

    public void Save(string message);

}

Second, redefine the DatabaseAccess that implements the IDataAccess interface:

public class DatabaseService: IDataService

{

    public void Save(string message)

    {

        Console.WriteLine("Save the message into the database");

    }

}

Third, change the member and constructor of the Logger class to use the IDataAccess interface instead of the DatabaseAccess class:

public class Logger

{

    private readonly IDataService _dataService;

 

    public Logger(IDataService dataService)

    {

        _dataService = dataService;

    }

 

    public void Log(string message)

    {

        _dataService.Save(message);

    }

}

By doing this, we can decouple the Logger and DatabaseService classes, making it easier to change one class without affecting each other.

Also, we can easily swap the DatabaseService class for a different class that implements the IDataService interface. For example, we can define the FileService class that saves a message into a text file by passing it to the Logger class.

 

Benefits of Dependency Inversion Principle:

1.     Create a flexible and maintainable codebase that is adaptable to change.

2.     Easier unit testing

3.     Promotes good design practices.

4.     Better code reusability.

5.     Clear Abstractions.

 

How do you implement DIP in C#?

To implement DIP, you should:

  1. Define abstractions using interfaces or abstract classes.
  2. Create concrete implementations of these abstractions for specific functionalities.
  3. Have high-level modules depend on abstractions, not concrete implementations.
  4. Inject dependencies into high-level modules via constructors or other methods.

  

Can you provide a real-world example of DIP in C#?

Sure, consider a logging system - we have two main classes DatabaseService and Logger.

The DatabaseService is a low-level module that provides database access.

The Logger is a high-level module that logs data.

The Logger class depends on the DatabaseService class directly. In other words, the high-level module (Logger) depends on the low-level module (DatabaseService).

 

Can you recommend tools or libraries to help implement DIP in C# projects?

While no specific tools or libraries exist exclusively for DIP, popular .NET dependency injection (DI) frameworks like built-in DI containers and third-party libraries like Autofac DI, UnityContainer DI, and NInject DI can help implement DIP effectively.

 

The syntax looks like:

   // Autofac DI

   var builder = new ContainerBuilder ();

   builder.RegisterInstance(new SqlConnection()).As<IDbConnection>();

  

   // UnityContainer DI

   IUnityContainer container = new UnityContainer ();

   container.RegisterType<IDbConnection, SqlConnection>();

  

   // NInject DI

   public class Bindings: NinjectModule {

      public override void Load() {

         Bind<IDbConnection>().To<SqlConnection>();

      }

   }

 

Dependency Injection:

Dependency Injection (DI) is a common technique used to implement the Dependency Inversion Principle (DIP). DI allows for easy substitution of implementations and promotes adherence to abstractions.

Dependency Injection (DI) involves providing dependencies to a class from an external source, typically through constructor parameters, setters, or methods.

For example, in Dependency Injection (DI) setup code, like Program.cs in .NET Core implementing for Logger looks like this:

builder.Services.AddTransient<ILog, Log>();


Dependency Inversion Principle vs Dependency Injection C#

The dependency Inversion Principle focuses on making high-level and low-level modules depend on abstractions. Dependency Injection is a technique for providing these abstractions to the modules at runtime.

Dependency Injection is an implementation technique for populating instance variables of a class.

For example, in some DI setup code, like Program.cs in .NET Core of implementing Dependency Injection:

builder.Services.AddTransient<ILog, Log>();


Dependency Injection is a practical technique that enables the implementation of Dependency Inversion by injecting dependencies externally. It's an implementation technique for populating instance variables of a class.

 

What are the different types of dependency injection?

Dependency Injection in .NET Core can be implemented using all three techniques:

1.     Constructor Injection

2.     Method Injection

3.     Property Injection

Let’s say we want to create a service to send a Hello message to users.

 

Step 1: Create a Hello Interface

public interface IHelloService

{

    string SayHello();

}

Step 2: Create a Class Implementing the Interface

public class HelloService : IHelloService

{

    public string SayHello()

    {

        return "Hello, This the hello message!";

    }

}

Step 3: Register the Hello Service with the DI Container

In your Startup.cs class, configure the dependency injection container, and this example uses the built-in .NET Core dependency injection container:

public void ConfigureServices(IServiceCollection services)

{

    //Added dependency injection for settings

     services.AddScoped<IHelloService, HelloService>();

    //Other dependency injections can be also added here using AddTransient or AddSingleton

    // services.AddTransient<IHelloService, HelloService>();

    // services.AddSingleton<IHelloService, HelloService>();

}

 

Step 4: Inject the Service into a Class Using Different Injection Techniques

Constructor Injection (1):

Constructor Injection involves injecting dependencies through a class’s constructor. Most common ways to apply Dependency Inversion in C#.

Let's see the Example:

// Define a class called HelloController.

public class HelloController

{

    // Declare a private field to store the IHelloService dependency.

    private readonly IHelloService _helloService;

    // Create a constructor that accepts an IHelloService instance as a parameter.

    public HelloController(IHelloService helloService)

    {

        // Assign the provided IHelloService instance to the private field.

        _helloService = helloService;

    }

    // Define a method called SayHello.

    public string SayHello()

    {

        // Use the injected _helloService to send the hellow message.

        return _helloService.SayHello();

    }

}

 

Method Injection (2):

Method Injection involves passing dependencies as parameters to methods where they are needed.

It is suitable when you want to inject a dependency only for a specific method:

// Define a class called HelloController

public class HelloController

{

    // Define a method called SayHello that accepts an IHelloService instance as a parameter.

    public string SayHello(IHelloService helloService)

    {

        // Use the injected helloService parameter to send the hello message.

        return helloService.SayHello();

    }

}

 

Property Injection (3):

Please note that Property Injection makes the HelloService property publicly accessible for injection, which can be considered less restrictive than Constructor Injection.

// Define a class called HelloController.

public class HelloController

{

    // Declare a public property of type IHelloService to allow property injection.

    public IHelloService HelloService { get; set; }

    // Define a method called SayHello.

    public string SayHello()

    {

        // Use the injected HelloService property to send hello message.

        return HelloService.SayHello();

    }

}

By Anil Singh | Rating of this article (*****)

Popular posts from this blog

39 Best Object Oriented JavaScript Interview Questions and Answers

Most Popular 37 Key Questions for JavaScript Interviews. What is Object in JavaScript? What is the Prototype object in JavaScript and how it is used? What is "this"? What is its value? Explain why "self" is needed instead of "this". What is a Closure and why are they so useful to us? Explain how to write class methods vs. instance methods. Can you explain the difference between == and ===? Can you explain the difference between call and apply? Explain why Asynchronous code is important in JavaScript? Can you please tell me a story about JavaScript performance problems? Tell me your JavaScript Naming Convention? How do you define a class and its constructor? What is Hoisted in JavaScript? What is function overloadin

List of Countries, Nationalities and their Code In Excel File

Download JSON file for this List - Click on JSON file    Countries List, Nationalities and Code Excel ID Country Country Code Nationality Person 1 UNITED KINGDOM GB British a Briton 2 ARGENTINA AR Argentinian an Argentinian 3 AUSTRALIA AU Australian an Australian 4 BAHAMAS BS Bahamian a Bahamian 5 BELGIUM BE Belgian a Belgian 6 BRAZIL BR Brazilian a Brazilian 7 CANADA CA Canadian a Canadian 8 CHINA CN Chinese a Chinese 9 COLOMBIA CO Colombian a Colombian 10 CUBA CU Cuban a Cuban 11 DOMINICAN REPUBLIC DO Dominican a Dominican 12 ECUADOR EC Ecuadorean an Ecuadorean 13 EL SALVADOR

25 Best Vue.js 2 Interview Questions and Answers

What Is Vue.js? The Vue.js is a progressive JavaScript framework and used to building the interactive user interfaces and also it’s focused on the view layer only (front end). The Vue.js is easy to integrate with other libraries and others existing projects. Vue.js is very popular for Single Page Applications developments. The Vue.js is lighter, smaller in size and so faster. It also supports the MVVM ( Model-View-ViewModel ) pattern. The Vue.js is supporting to multiple Components and libraries like - ü   Tables and data grids ü   Notifications ü   Loader ü   Calendar ü   Display time, date and age ü   Progress Bar ü   Tooltip ü   Overlay ü   Icons ü   Menu ü   Charts ü   Map ü   Pdf viewer ü   And so on The Vue.js was developed by “ Evan You ”, an Ex Google software engineer. The latest version is Vue.js 2. The Vue.js 2 is very similar to Angular because Evan You was inspired by Angular and the Vue.js 2 components looks like -

React | Encryption and Decryption Data/Text using CryptoJs

To encrypt and decrypt data, simply use encrypt () and decrypt () function from an instance of crypto-js. Node.js (Install) Requirements: 1.       Node.js 2.       npm (Node.js package manager) 3.       npm install crypto-js npm   install   crypto - js Usage - Step 1 - Import var   CryptoJS  =  require ( "crypto-js" ); Step 2 - Encrypt    // Encrypt    var   ciphertext  =  CryptoJS . AES . encrypt ( JSON . stringify ( data ),  'my-secret-key@123' ). toString (); Step 3 -Decrypt    // Decrypt    var   bytes  =  CryptoJS . AES . decrypt ( ciphertext ,  'my-secret-key@123' );    var   decryptedData  =  JSON . parse ( bytes . toString ( CryptoJS . enc . Utf8 )); As an Example,   import   React   from   'react' ; import   './App.css' ; //Including all libraries, for access to extra methods. var   CryptoJS  =  require ( "crypto-js" ); function   App () {    var   data

AngularJs input date format calendar

Table of Context bout  the input date.  Click for live demo on plnker 1. Allow to use of a custom date format like "yyyy/MM/dd" or "yyyy-MM-dd" etc. 2. Allow to check the input date typed by the user is correct or not. 1 2 3 4 //The model must be a Date object, otherwise Angular will throw an error. //The error is Invalid Date objects will be rendered as an empty string. i.e. The dates whose getTime() is NaN. //The model must be a Date object, otherwise Angular will throw an error. //The error is Invalid Date objects will be rendered as an empty string. i.e. The dates whose getTime() is NaN. The Example 1 code as given below. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 <!doctype html> <html lang= "en" > <head>      <meta charset= "utf-8" />      <script src= " http://ajax.googleapis.com/ajax/lib