zgba Network

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 ready-to-use objects through the constructor. Base DI types Microsoft.Extensions.DependencyInjection has 3 base lifetime types. This is: Singleton Scoped Transient A singleton lives for the entire duration of the application’s execution. Just - it’s creating one for-all. Like AppDbContext or another. A scoped lives for every HTTP-request as example. Every HTTP-Request has own Scope, scoped lives in scope like IUserRepository, IAuthService. A transient lives for the shortest time. It is created every time it is requested from the DI container. Like IEmailSender, IValidator, or lightweight helper services. Let’s create our own DI I wrote simple service like this namespace ExampleProject; public interface IMyService { Task GetHello(string name); } public class MyService : IMyService { public async Task GetHello(string name) { await Task.Delay(150); return “Hello, {name}!”; } } Now let’s add this to our controller (MyController) method public async Task Get(string name) Let’s replace that method for this [HttpGet] public async Task Get(string name) { var start = DateTime.Now; var hello = await service.GetHello(name); var end = DateTime.Now; return Ok(“{hello} It took {end - start} to respond.”); } So, we need to replace class declaration to add constructor to this public class MyController(IMyService service) : ControllerBase Now let’s add our Service to DI using ExampleProject; using Scalar.AspNetCore; var builder = WebApplication.CreateBuilder(args); builder.Services.AddOpenApi(); builder.Services.AddControllers(); builder.Services.AddScoped<IMyService, MyService>(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.MapOpenApi(); app.MapScalarApiReference(); } app.MapControllers(); app.Run(); Testing Now run, and open in browser localhost:[your port]/scalar Press [Test Request], and press [Send] And now listened: Hello, sabaka! It took 00:00:00.1608323 to respond. In next chapters we learn Databases, Clean Architecture and more

View original article