Student learning series · Lesson 4 of 6
Register services and observe scoped lifetimes with a request identifier example.
What you will learn
Dependency injection lets a consumer receive an object from a service container. Registration tells the container how to construct it and how long to reuse it. This separates object creation from the code that uses it.
1. Create the project
dotnet new web -n ServicesLesson
cd ServicesLessonReplace Program.cs and request /request-stamp twice. Compare the identifiers within each response and between responses.
2. Complete Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<RequestStamp>();
var app = builder.Build();
app.MapGet("/request-stamp", (RequestStamp first, RequestStamp second) =>
Results.Ok(new
{
first = first.Value,
second = second.Value,
sameWithinRequest = first.Value == second.Value
}));
app.Run();
class RequestStamp
{
public Guid Value { get; } = Guid.NewGuid();
}
3. Run and observe
dotnet run --no-launch-profile -- --urls http://127.0.0.1:5070Stop the server with Ctrl+C before starting the next lesson on the same port. For web lessons, visit the listed GET path at http://127.0.0.1:5070 in your browser. Use an HTTP client for POST, PUT and DELETE with Content-Type: application/json.
Each response has first, second and sameWithinRequest.
With AddScoped, first equals second and sameWithinRequest is true.
A later request receives a different identifier.4. Understand the code
The two handler parameters request the same registered service type. Scoped means one instance within the HTTP request scope. Transient creates a new instance for each resolution. Singleton reuses one instance across the application and needs thread-safe mutable state.
Practice exercise
Replace AddScoped with AddTransient, then AddSingleton. Restart after each edit and predict the values.
Self-check and answer
Transient produces two different values in one response. Singleton keeps one value across requests until restart. A singleton should not capture a scoped dependency; doing so breaks the intended lifetime.
Study notes
Type the example yourself, run it, change one behavior, and explain the result in your own words. Keep each lesson in its own project. These examples were compiled with .NET SDK 9.0.306; select a currently supported SDK for new study projects. The course teaches modern .NET and ASP.NET Core, rather than obsolete .NET Core 3.1 or classic Web Forms.
Return to the .NET Core student learning path · Official Microsoft documentation · .NET support policy
No comments:
Post a Comment
Please do not enter any spam link in the comment box.