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:
- 1. Single-Responsibility Principle (SRP)
- 2. Open-closed principle (OCP)
- 3. Liskov Substitution Principle (LSP)
- 4. Interface Segregation Principle (ISP)
- 5. Dependency Inversion Principle (DIP)
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:
- Define abstractions using interfaces or abstract classes.
- Create concrete implementations of these abstractions for specific functionalities.
- Have high-level modules depend on abstractions, not concrete implementations.
- 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();
}
}