[go: up one dir, main page]

0% found this document useful (0 votes)
17 views1 page

Dependency Injection DI

Dependency Injection (DI) is a design pattern that enhances code reusability, testability, and maintainability in ASP.NET Core. The framework offers a built-in IoC container that supports various service lifetimes: Singleton, Scoped, and Transient. An example demonstrates how to register and inject a service into a controller, illustrating the practical application of DI in ASP.NET Core development.

Uploaded by

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

Dependency Injection DI

Dependency Injection (DI) is a design pattern that enhances code reusability, testability, and maintainability in ASP.NET Core. The framework offers a built-in IoC container that supports various service lifetimes: Singleton, Scoped, and Transient. An example demonstrates how to register and inject a service into a controller, illustrating the practical application of DI in ASP.NET Core development.

Uploaded by

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

Dependency Injection (DI) in ASP.

NET Core

1. Introduction
Dependency Injection (DI) is a design pattern used to achieve Inversion of Control (IoC) between cl

2. Benefits of DI
- Promotes code reusability and testability
- Reduces class coupling
- Improves code maintainability
- Enables better separation of concerns

3. DI in ASP.NET Core
ASP.NET Core provides a built-in IoC container that supports constructor injection, method injection

4. Service Lifetimes
- Singleton: A single instance is created and shared throughout the application's lifetime.
- Scoped: A new instance is created per request.
- Transient: A new instance is created each time it is requested.

5. Example
public interface IMyService {
string GetData();
}

public class MyService : IMyService {


public string GetData() => "Hello from MyService";
}

// Registering in Startup.cs
services.AddScoped<IMyService, MyService>();

// Injecting into a controller


public class HomeController : Controller {
private readonly IMyService _service;
public HomeController(IMyService service) {
_service = service;
}
public IActionResult Index() {
var data = _service.GetData();
return View("Index", data);
}
}

You might also like