In the previous tutorial of this tutorial series, you have learned about component in basic. In this tutorial, you will learn another building block of Blazor: Dependency Injection. Dependency Injection is a technique that lets you manage the website's state.
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.
CartService.cs in your Services folder. The Services folder was created in the previous tutorial in this tutorial section.public List<Product> SelectedItems { get; set; } = new();
public void AddProductToCart(Guid productId)
{
var product = ProductProviderService.Products.First(p => p.Id == productId);
if (SelectedItems.Contains(product) is false)
{
SelectedItems.Add(product);
}
}
CartService in the Program.cs.builder.Services.AddScoped<CartService>();
Next step, we are going to use the CartService we just created to store the cart information.
ProductList.razor we created at the previous tutorial.CartService. Add the following code to the directive section (at the start of the component).@inject CartService CartService
@code {
...
private void Buy(Guid productId)
{
CartService.AddProductToCart(productId);
}
}
@onclick to the Buy button.<button class="btn btn-primary" type="button" @onclick="() => Buy(product.Id)">Buy</button>
After the user is able to put product to the cart, we will let them review their cart.
Checkout.razor in the Pages folder.CartService. Add the following code to the directive section (at the start of the component).@inject CartService CartService
ProductList component which we have created at the previous tutorial to display the products in the cart. Add the following code to the UI section (below the directive section).<h3>You have @CartService.SelectedItems.Count in cart:</h3> <ProductList Products="CartService.SelectedItems"></ProductList>
You can see the result as follow:
