Your first ASP.NET App: Dependency Injection
Hello! In this tutorial we will build your own ASP.NET Service Dependency Injection! Requirements IDE like Visual Studio/JetBrains Rider .NET >= 10 Base C# skill CPU (manually) What is DI DI (Dependency Injection) in C# is a design pattern where a class receives its dependencies from the outside instead of creating them itself.In short: it replaces hardcoded new operators with passing…
This tutorial guides you through the process of creating your first ASP.NET application using Dependency Injection (DI). Dependency Injection is a design pattern that enables classes to receive their dependencies from an external source instead of creating them internally. It replaces hardcoded new operators with passing ready-to-use objects via constructors.
The three main lifetime types for dependency injection in Microsoft.Extensions.DependencyInjection are Singleton, Scoped, and Transient. A Singleton instance exists throughout the entire application's runtime, creating a single instance shared by all. Scoped instances are created for each HTTP request, with a separate instance for every request. Transient instances are created every time they are requested from the DI container, making them the shortest-lived of the three options.
To demonstrate DI, we create a simple service called IMyService with an asynchronous method GetHello that accepts a name parameter and returns a greeting message. We then implement this service in a class called MyService, which also implements the IMyService interface.
In our controller MyController, we update the Get method to accept an IMyService instance through its constructor. This allows the controller to access the service's functionality without creating the service itself.
Next, we configure our DI container within the WebApplication's CreateBuilder method. We add our service to the container using the AddScoped method, specifying the service's type and implementation. This ensures that a new instance of MyService is created for every scoped dependency within the application.
Finally, we run the application and test it by sending a request to the endpoint /scalar/Test Request. The application responds with a greeting message from our service, along with the time it took to generate the response. This tutorial sets the stage for further exploration of databases, clean architecture, and other advanced topics in upcoming chapters.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.