
一步步教你進行 Python REST API 身份驗證
> Repository 模式旨在為領域與數據映射層之間提供中介,使業務邏輯層無需關注數據存儲細節,就像一個“數據庫集合”的接口。
倉儲就是一個專門存放“數據庫調用”的地方,你把 DbContext
的增刪改查都放在這里,需要時在業務或控制器中“即插即用”,就像隨時取用一個獨立模塊。
public class Pokemon
{
public int Id { get; set; }
public string Name { get; set; }
// … 其他屬性
}
在 Interfaces/IPokemonRepository.cs
中定義倉儲契約:
public interface IPokemonRepository
{
IReadOnlyCollection < Pokemon > GetPokemons();
// 若有增刪改查,可繼續擴展:
// Pokemon GetPokemon(int id);
// bool CreatePokemon(Pokemon p);
// bool UpdatePokemon(Pokemon p);
// bool DeletePokemon(int id);
}
在 Repositories/PokemonRepository.cs
中實現接口:
public class PokemonRepository : IPokemonRepository
{
private readonly AppDbContext _context;
public PokemonRepository(AppDbContext context)
{
_context = context;
}
public IReadOnlyCollection < Pokemon > GetPokemons()
{
// 從 DbContext 中讀取所有 Pokemons,并按 Id 排序
return _context.Pokemons
.OrderBy(p = > p.Id)
.ToList();
}
}
> 要點:ToList()
明確觸發查詢,并轉換為不可變集合類型。
在 Controllers/PokemonController.cs
中注入并使用:
[ApiController]
[Route("api/[controller]")]
public class PokemonController : ControllerBase
{
private readonly IPokemonRepository _pokemonRepo;
public PokemonController(IPokemonRepository pokemonRepo)
{
_pokemonRepo = pokemonRepo;
}
[HttpGet]
public ActionResult < IReadOnlyCollection < Pokemon > > GetPokemons()
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var list = _pokemonRepo.GetPokemons();
return Ok(list);
}
}
在 Program.cs
中注冊服務:
builder.Services.AddScoped < IPokemonRepository, PokemonRepository > ();
通過本文示例,你已掌握在 ASP.NET Core 項目中從零搭建 Repository 模式的全流程,讓你的 API 更加松耦合、易維護、可測試。繼續打磨、優化,項目將更具健壯性與可擴展性!
原文引自YouTube視頻:https://www.youtube.com/watch?v=-LAeEQSfOQk