
深入解析API网关策略:认证、授权、安全、流量处理与可观测性
在许多 ASP.NET Core 项目中,你可能会看到控制器(Controller)直接引用 DbContext
并写入查询逻辑,导致代码难以维护、难以测试。Repository 模式提供了一种抽象层,将所有与数据库交互的逻辑集中到“仓储”中,实现与业务逻辑层的松耦合。本文用“宝可梦(Pokemon)”示例,带你一步步落地实践。
> 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