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/ 10
Dot Net
Dependency Injection 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.
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
• In a large project with multiple classes depending on
MessageWriter, the configuration code becomes scattered across the app.
• This implementation is difficult to unit test. The app
should use a mock or stub MessageWriter class, which isn't possible with this approach. Dependency Injection • Dependency injection addresses these problems through:
• The use of an interface or base class to abstract the dependency implementation.
• Registration of the dependency in a service container. .NET provides a built-in service container, IServiceProvider. • Services are typically registered at the app's start-up and appended to an IServiceCollection. • Once all services are added, you use BuildServiceProvider to create the service container. • Injection of the service into the constructor of the class where it's used. The framework takes on the responsibility of creating an instance of the dependency and disposing of it when it's no longer needed. Dependency Injection: Example • IMessageWriter interface defines the Write method:
public interface IMessageWriter
{ void Write(string message); } Dependency Injection: Example
public class MessageWriter : IMessageWriter
{ public void Write(string message) { Console.WriteLine($"MessageWriter.Write(message: \"{message}\")"); } } Dependency Injection: Example