Vijay Yadav
What is Dependency Injection (DI) in .NET, and how does it work? Can you provide an example of how DI is implemented in ASP.NET Core?
By Vijay Yadav in .NET Core on Aug 13 2024
  • Venkatesh Mahendru
    Aug, 2024 22

    **Dependency Injection (DI)** is a pattern used in .NET to achieve Inversion of Control (IoC) between classes and their dependencies. Instead of a creating Object of concrete classes directly create an object with abstraction.**Major Benifit is:** Loosely Coupled.## How does it works? In ASP.NET Core, DI is built into the framework and is configured in the Startup.cs or Program.cs file as per .Net core Version. The DI container is responsible for creating instances of services and injecting them where needed.# **Steps to Implement Dependency Injection in ASP.NET Core:** Define an Interface:Create an interface that defines the contract for the service. Implement the Interface:Create a class that implements the interface. Register the Service:Register the service in the DI container in the Startup.cs file. Inject the Service:Use constructor injection to inject the service into the consuming class.1) Define an Interface: public interface IGreetingService {string Greet(string name); }2) Implement the Interface: public class GreetingService : IGreetingService {public string Greet(string name){return $"Hello, {name}!";} }3) Register the Service```csharp public class HomeController : Controller {private readonly IGreetingService _greetingService;// Constructor injection of the IGreetingServicepublic HomeController(IGreetingService greetingService){_greetingService = greetingService;}public IActionResult Index(){var message = _greetingService.Greet("World");ViewBag.Message = message;return View();} }``` public class Startup {public void ConfigureServices(IServiceCollection services){// Register the GreetingService with a scoped lifetimeservices.AddScoped();// Add other services like MVCservices.AddControllersWithViews();}// Other methods like Configure()... }4) Inject the Service public class HomeController : Controller {private readonly IGreetingService _greetingService;// Constructor injection of the IGreetingServicepublic HomeController(IGreetingService greetingService){_greetingService = greetingService;}public IActionResult Index(){var message = _greetingService.Greet("World");ViewBag.Message = message;return View();} }5) Use the data in View or in Client Application.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS