我正在學習泛型,并且想知道通用控制器、服務和 ef 核心 repo 設計的外觀。
我的案例:假設一個傳入的帖子請求將智能手機和鍵盤物件添加到智能手機和鍵盤表
我的存盤庫設定是
public class GenericRepository<TEntity> : IGenericRepository<TEntity>
where TEntity : class, IProductGenericEntities
{
private readonly MyDbContext _db;
public GenericRepository(MyDbContext db)
{
_db = db;
}
public async Task<bool> AddProduct(TEntity entity)
{
try
{
_db.Set<TEntity>().AddAsync(entity);
return (await _db.SaveChangesAsync()) > 0;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
}
還有我的服務
public class ProductService<TEntity> : IProductService<TEntity>
where TEntity : class
{
private readonly IGenericRepository<TEntity> _repo;
public ProductService(IGenericRepository<TEntity> repo)
{
_repo = repo;
}
public async Task<bool> AddProduct(TEntity entity)
{
return await _repo.AddProduct(entity);
}
}
還有我的 Controller.cs
[ApiController]
[Route("api/[controller]")]
public class ProductController
{
private readonly IProductService<Keyboards> _keyService;
private readonly IProductService<Smartphones> _smartService;
public ProductController(IProductService<Keyboards> keyService, IProductService<Smartphones> smartService)
{
_keyService = keyService;
_smartService = smartService;
}
[HttpPost("Post-generated-items")]
public async Task<ActionResult> PostProducts(List<TEntity> entities)
{
foreach(var item in entities)
{
and sort the objects here
}
}
}
初始化 2 個 IProductServices 并將傳入物件排序到控制器上的正確 DI 是否正確?
private readonly IProductService<Keyboards> _keyService;
private readonly IProductService<Smartphones> _smartService;
有沒有辦法通過檢測傳入的物件型別來使其更加自動化,然后一直初始化它到 repo,所以我不需要 2 個 IProductService<>?
還是我對通用服務層做錯了什么?
uj5u.com熱心網友回復:
好的,所以你的方法是完全有效的,我不會擔心初始化兩個存盤庫,因為它們本質上是空的記憶體虎鉗,因為它們只是參考存在的 DbContext ,默認情況下它是在Scoped生命周期中注冊的。
有時您需要使用多個存盤庫來完成手頭的任務。我建議采用非通用服務方法。這樣,您可以使 ProductsService 注入所有需要的通用存盤庫,并可以協調它們的作業以實作用例目標。
對于更復雜的情況,您不妨研究一下 UOW(作業單元)模式。
回答你的問題:
有沒有辦法通過檢測傳入的物件型別來使其更加自動化,然后一直初始化它到 repo,所以我不需要 2 個 IProductService<>?
您可能會撰寫一些代碼來使用反射為您做這件事,但我建議不要這樣做。通過專門初始化您的存盤庫,您可以減少自己出錯的可能性,并且代碼變得更加自我記錄。
例如,現在您有一個控制器,它向 DI 請求兩項服務,并立即讓您了解該控制器中正在發生的事情。另一方面,如果一切都是通用的,那么您最終會得到一個“無所不能”的巨大意大利面條結。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/478812.html
上一篇:用于自旋向上和向下粒子的類?
