Problem statement
Register four services with the right dependency-injection lifetimes, so an API keeps one shared counter across requests and a separate tag for each request.
Requirements
The controller, the services and the database context are already provided. Your task has one part: register the four services in AddApplicationServices in RequestTrackingApi/Services/ServiceRegistration.cs.
The lifetime you register a service with decides how often ASP.NET Core creates it:
- AddSingleton: one instance for the whole application
- AddScoped: one instance per HTTP request, shared by everything in that request
- AddTransient: a new instance every time it is injected
For example, this line registers SystemClock as the one shared IClock (it is not part of this task):
services.AddSingleton<IClock, SystemClock>();
A singleton must not depend on a scoped service. If it does, the app stops at startup with an error.
ServiceRegistration
- ICounterStore with CounterStore: one instance for every request, so counter in GET /diagnostics grows by 1 on each call (1, then 2, then 3)
- IRequestScopedTag with RequestScopedTag: one instance per request, so directTag and consumerTag are the same within a request, and different on the next request
- ITagConsumer with TagConsumer: it must get the same tag as the controller, so make it scoped or transient
- IItemRepository with ItemRepository: it uses the scoped TrackingDbContext, so make it scoped or transient
TrackingController (provided)
- GET /diagnostics answers 200 with counter (from ICounterStore.Increment), directTag (the tag injected into the controller) and consumerTag (the tag seen by ITagConsumer)
- GET /items answers 200 with the five seeded items, ordered by id
Sample Requests & Responses
GET /diagnostics
Response (200 OK):
{
"counter": 1,
"directTag": "10871d11-4819-4fed-a15b-d72d6bb21ccb",
"consumerTag": "10871d11-4819-4fed-a15b-d72d6bb21ccb"
}
GET /diagnostics (the next request)
Response (200 OK):
{
"counter": 2,
"directTag": "4824ee2b-ea4d-47ae-94d6-37853620d6e6",
"consumerTag": "4824ee2b-ea4d-47ae-94d6-37853620d6e6"
}
Your GUIDs will be different, because each request creates a new tag.
GET /items
Response (200 OK):
[
{ "id": 1, "name": "Widget", "category": "hardware" },
{ "id": 2, "name": "Gadget", "category": "hardware" },
{ "id": 3, "name": "Manual", "category": "docs" },
{ "id": 4, "name": "License", "category": "docs" },
{ "id": 5, "name": "Sticker", "category": "swag" }
]
