I am using Dependency Injection for a Shopping Cart, In the layout page, I want to get a Brand new Price from the database in the ShoppingCart and it does not, it gets the Price from the allready assigned Price from Index of HomeController,
Is there a way I can acomplish this ?
At starup
services.AddScoped<ShoppingCart>();
In the Controller using the Index, so when I click on the HomeController I belive the yoContext gets assigned the Price value and takes it all the way to the ShoppingCart class
public class HomeController : Controller { private yoContext db; public HomeController(yoContext context) { db = context; } public IActionResult Index() { foreach(var product in db.Products) { var prod = db.Products.Single(p => p.productId == product.productId);
prod.price = // Here I will do other calculations to get the Price that I want product.price = prod.price ; } return View(db.Products.ToList());//Here the db.Products have the new assigned Price } }
And in the Service class which is the shoppingCart class Here I get the Product Price assigned from Index and I want to get the Price from the database value instead
public class ShoppingCart { private yoContext db; public ShoppingCart(yoContext context) { db = context; } public decimal GetTotal() { foreach (var product in db.Products) { var prod = db.Products.Single(p => p.productId == product.productId); product.price = prod.price; // Here I get the assigned value from Index of HomeController, but I want to get the value of the database } }
And finally here is the layout page
@inject yo.Services.ShoppingCart cart
<a asp-action="Index" asp-controller="Cart" class="navbar-brand">
@cart.GetQty()
<i class="glyphicon glyphicon-shopping-cart "></i>
@cart.GetTotal()
</a>
And I get the wrong Total, because of the assigned value from HomeContrller IActionResult Index