0% found this document useful (0 votes)
14 views5 pages

Dependency Injection

Uploaded by

musabinshabeer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views5 pages

Dependency Injection

Uploaded by

musabinshabeer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Dependency Injection

• NET supports the dependency injection (DI) software design


pattern, which is a technique for achieving Inversion of Control
(IoC) between classes and their dependencies.
• Dependency injection (DI) is a design pattern that helps achieve loose coupling, a
design goal that aims to reduce dependencies between components of a system

• Dependency injection in .NET is a built-in part of the framework,


along with configuration, logging, and the options pattern.

• A dependency is an object that another object depends on.


Dependency Injection: Example

public class MessageWriter


{
public void Write(string message)
{
Console.WriteLine($"MessageWriter.Write(message:
\"{message}\")");
}
}
Dependency Injection: Example
• MessageWriter class is a dependency of the Worker class.

public class Worker : BackgroundService


{
private readonly MessageWriter _messageWriter = new();

protected override async Task ExecuteAsync(CancellationToken stoppingToken)


{
while (!stoppingToken.IsCancellationRequested
{
_messageWriter.Write ($"Worker running at: {DateTimeOffset.Now}");
await Task.Delay(1_000, stoppingToken);
}
}
}
Dependency Injection

• The class creates and directly depends on the


MessageWriter class.
• Hard-coded dependencies are problematic and should
be avoided for the following reasons:
• To replace MessageWriter with a different
implementation, the Worker class must be modified.
• If MessageWriter has dependencies, they must also be
configured by the Worker class.
Dependency Injection: Example
• IMessageWriter interface defines the Write method:

public interface IMessageWriter


{
void Write(string message);
}

You might also like