Problem statement
Replace hand-written new calls with constructor injection, so the container builds the order controller, its service and every part below it.
Requirements
Right now OrdersController creates its OrderService with new, and OrderService creates its parts with new. Your task has three parts: register the services in OrderServiceApi/Program.cs, and change the constructors in OrderServiceApi/Controllers/OrdersController.cs and OrderServiceApi/Services/OrderService.cs.
With constructor injection, a class lists what it needs as constructor parameters, and the container passes them in. PricingCalculator already works this way: its constructor receives IDiscountPolicy and ITaxCalculator.
When you are done, the container builds this chain:
OrdersController
IOrderService -> OrderService
IOrderRepository -> OrderRepository
IPricingCalculator -> PricingCalculator
IDiscountPolicy -> StandardDiscountPolicy
ITaxCalculator -> StandardTaxCalculator
IAuditLog -> InMemoryAuditLog
Program.cs
- Register each of the six interfaces above with its class, using AddScoped
OrdersController
- The controller receives IOrderService through its constructor and keeps it in orderService, instead of creating it with new
OrderService
- The constructor receives IOrderRepository, IPricingCalculator and IAuditLog and keeps each one in its field
- None of them is created with new
GetOrder is already written. Every part has an InstanceId, and the graph in each response lists the parts that were used, so you can see that they came from the container.
Sample Requests & Responses
Your instance ids will be different. Decimal results keep the decimal places from the calculations, so 18 is printed as 18.000000.
GET /orders/1
Response (200 OK):
{
"orderId": 1,
"customer": "Acme Corp",
"lines": [
{ "sku": "WIDGET-1", "quantity": 2, "unitPrice": 50.00 },
{ "sku": "BOLT-9", "quantity": 10, "unitPrice": 15.00 }
],
"subtotal": 250.00,
"discount": 25.0000,
"tax": 18.000000,
"total": 243.000000,
"graph": [
{ "component": "OrderService", "instanceId": "ebbdf4a9-8bbf-4d3a-80c4-b41d543d3931" },
{ "component": "OrderRepository", "instanceId": "a8136dbb-9d66-4014-b152-90c909d0c653" },
{ "component": "PricingCalculator", "instanceId": "170fb697-9ff0-42f9-b562-3e597f8840dd" },
{ "component": "StandardDiscountPolicy", "instanceId": "e82a9a58-7566-43e5-9ba0-00e587e4c8b1" },
{ "component": "StandardTaxCalculator", "instanceId": "dc863fff-84b9-4598-9865-d3604af7ac0e" },
{ "component": "InMemoryAuditLog", "instanceId": "6003e04f-381a-4eda-a342-2a24f7cc9153" }
]
}
GET /orders/99
Response (404 Not Found).
