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

nullinjectorerror no provider for httpclient angular 17

In Angular 17 where the standalone true option is set by default, the app.config.ts file is generated in src/app/ and provideHttpClient(). We can be added to the list of providers in app.config.ts Step 1:   To provide HttpClient in a standalone app we could do this in the app.config.ts file, app.config.ts: import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { provideClientHydration } from '@angular/platform-browser'; //This (provideHttpClient) will help us to resolve the issue  import {provideHttpClient} from '@angular/common/http'; export const appConfig: ApplicationConfig = {   providers: [ provideRouter(routes),  provideClientHydration(), provideHttpClient ()      ] }; The appConfig const is used in the main.ts file, see the code, main.ts : import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from ...

How To Optimizing Database Performance: Tips and Techniques for Developers

Best Practices for Optimizing Database Performance: Tips and Techniques for Developers Navigating the labyrinth of database performance optimization can often seem like a daunting task for many professionals. Especially for database developers, mastering this critical skill has immense value, as it enhances both the efficiency and responsiveness of their applications.  Effective database performance optimization leads to faster data retrieval and smoother transactions.  A key challenge, however, lies in knowing  how to hire database developers who are well-versed in optimization techniques. The market is flooded with many professionals, but finding the right expert who understands the intricacies of database performance can be like looking for a needle in a haystack. Employers need to seek those who are not only proficient in their craft but also updated with the latest optimization practices. This guide, therefore, not only aims to provide developers with a compre...

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 ...

Top 15+ Angular 17 Interview Questions Answers | For Experienced Professionals as well

G Google team released the latest version of Angular – Angular 17 on November 6, 2023, creating a significant milestone for the super fast front-end development. What Are the New Features in Angular 17? 1.       Angular 17 is the highly anticipated release for the community, bringing many new exciting features, updates, and improvements. 2.       New Syntax for Control Flow in Templates - new @if, @switch, @for, @case, @empty @end control flow syntax 3.       Deferred Loading - @defer partial template 4.       The Angular signals API 5.       Angular SSR and client hydration 6.       Automatic Migration to Build-in Control Flow 7.       Build Performance with ESBuild 8.       By default, set this newly generated component as a standalone, and now we don't have an app module file. To use (ng...

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...