This tutorial is a continuation of the previous tutorial. You are going to learn how to create a service using the Dependency Injection technique. In this tutorial:
You can download the example code used in this topic on GitHub.
This cart service will hold the information about the product which is selected by the user. This is also known as storing the website's state. There are many places to store that state. For the sake of simplicity, we are going to store the website's state in the memory.
CartState.cs
as follows:public class CartState { private readonly HttpClient _httpClient; public List<Product> SelectedItems { get; set; } = new(); public CartState(HttpClient httpClient) { _httpClient = httpClient; } public async Task AddProductToCartAsync(Guid productId) { if (SelectedItems.Any(p => p.Id == productId) is false) { var products = await _httpClient.GetFromJsonAsync<List<Product>>("sample-data/products.json") ?? new(); var product = products.First(p => p.Id == productId); SelectedItems.Add(product); } } }
CartState
to the Dependency Injection. Open your Program.cs
and add the following code:builder.Services.AddScoped<CartState>();
Once you have the cart service, the next step is to let the users store their cart information.
ProductDisplay.razor
we have created in the previous tutorial.@inject CartState CartState
... @if (DisplayBuyButton) { <button class="btn btn-primary" type="button" @onclick="_ => CartState.AddProductToCartAsync(Product.Id)">Buy</button> } ... @code { ... [Parameter] public bool DisplayBuyButton { get; set; } = false; }
ProductList.razor
and pass the DisplayBuyButton="true"
to the Product
component.... <ProductDisplay Product="product" DisplayBuyButton="true"/>
You can see the following result:
After the user is able to put product to the cart, we will let them review their cart.
Checkout.razor
.@inject CartState CartState
<span>You have @CartState.SelectedItems.Count item(s) in your cart.</span> @foreach (var selectedItem in CartState.SelectedItems) { <ProductDisplay Product="selectedItem" /> }
You can see the following result when you put some products in the cart: