將StoreContext DI注入到ProductService 類別中
並取代原先兩個取商品清單跟詳細資訊兩個action
using MyReact1.Domain;
using MyReact1.Models;
namespace MyReact1.Services
{
public class ProductService
{
private readonly StoreContext dbContext;
public ProductService(StoreContext dbContext)
{
this.dbContext = dbContext;
}
public ProductModel GetProductList()
{
var products = dbContext.Products;
var model = new ProductModel();
foreach (var product in products)
{
model.Products.Add(new ProductModel.ProductListItem
{
Id = product.Id,
Description = product.Description,
Name = product.Name
});
}
return model;
}
public ProductDetailsModel GetDetails(int id)
{
var product = dbContext.Products.Find(id);
return new ProductDetailsModel
{
Id = product.Id,
Name = product.Name,
Description = product.Description,
Price = product.Price
};
}
}
}
改寫ProductController
將ProductService一樣透過DI注入方式引入到Controller做方法存取
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyReact1.Models;
using MyReact1.Services;
namespace MyReact1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
private readonly ProductService productService;
public ProductController(ProductService productService)
{
this.productService = productService;
}
public IActionResult List()
{
ProductModel model = productService.GetProductList();
return Ok(model);
}
// -> /api/Product/10
[HttpGet("{id}")]
public IActionResult Details(int id)
{
return Ok(productService.GetDetails(id));
}
}
}
記得在Program.cs相關Dbcontext和Service都需要先進行服務註冊
在.net core服務註冊中生命週期(IoC容器生命週期)
又有細分為如下幾種
Transient:每次被請求都會創建新的實體
Transient objects are always different; a new instance is provided to every controller and every service.
Scoped:每次Web請求會創建一個新實體,直到web請求結束就銷毀。
Scoped objects are the same within a request, but different across different requests.
Singleton:一旦被創建實體就會持續一直用,直到應用停止才銷毀。
Singleton objects are the same for every object and every request.
更詳細可參考
.NET Core第12天_服務依賴注入_IoC容器生命週期_ConfigureServices
https://coolmandiary.blogspot.com/2021/07/net-core12iocconfigureservices.html