系列導航
需求
經常寫CRUD程序的小伙伴們可能都經歷過定義很多Repository
接口,分別做對應的實現,依賴注入並使用的場景。有的時候會發現,很多分散的XXXXRepository
的邏輯都是基本一致的,於是開始思考是否可以將這些操作抽象出去,當然是可以的,而且被抽象出去的部分是可以不加改變地在今后的任何有此需求的項目中直接引入使用。
那么我們本文的需求就是:如何實現一個可重用的Repository
模塊。
長文預警,包含大量代碼。
目標
實現通用Repository
模式並進行驗證。
原理和思路
通用的基礎在於抽象,抽象的粒度決定了通用的程度,但是同時也決定了使用上的復雜度。對於自己的項目而言,抽象到什么程度最合適,需要自己去權衡,也許后面某個時候我會決定自己去實現一個完善的Repository
庫提供出來(事實上已經有很多人這樣做了,我們甚至可以直接下載Nuget包進行使用,但是自己親手去實現的過程能讓你更好地去理解其中的原理,也理解如何開發一個通用的類庫。)
總體思路是:在Application
中定義相關的接口,在Infrastructure
中實現基類的功能。
實現
通用Repository實現
對於要如何去設計一個通用的Repository
庫,實際上涉及的面非常多,尤其是在獲取數據的時候。而且根據每個人的習慣,實現起來的方式是有比較大的差別的,尤其是關於泛型接口到底需要提供哪些方法,每個人都有自己的理解,這里我只演示基本的思路,而且盡量保持簡單,關於更復雜和更全面的實現,GIthub上有很多已經寫好的庫可以去學習和參考,我會列在下面:
很顯然,第一步要去做的是在Application/Common/Interfaces
中增加一個IRepository<T>
的定義用於適用不同類型的實體,然后在Infrastructure/Persistence/Repositories
中創建一個基類RepositoryBase<T>
實現這個接口,並有辦法能提供一致的對外方法簽名。
IRepository.cs
namespace TodoList.Application.Common.Interfaces;
public interface IRepository<T> where T : class
{
}
RepositoryBase.cs
using Microsoft.EntityFrameworkCore;
using TodoList.Application.Common.Interfaces;
namespace TodoList.Infrastructure.Persistence.Repositories;
public class RepositoryBase<T> : IRepository<T> where T : class
{
private readonly TodoListDbContext _dbContext;
public RepositoryBase(TodoListDbContext dbContext) => _dbContext = dbContext;
}
在動手實際定義IRepository<T>
之前,先思考一下:對數據庫的操作都會出現哪些情況:
新增實體(Create)
新增實體在Repository
層面的邏輯很簡單,傳入一個實體對象,然后保存到數據庫就可以了,沒有其他特殊的需求。
IRepository.cs
// 省略其他...
// Create相關操作接口
Task<T> AddAsync(T entity, CancellationToken cancellationToken = default);
RepositoryBase.cs
// 省略其他...
public async Task<T> AddAsync(T entity, CancellationToken cancellationToken = default)
{
await _dbContext.Set<T>().AddAsync(entity, cancellationToken);
await _dbContext.SaveChangesAsync(cancellationToken);
return entity;
}
更新實體(Update)
和新增實體類似,但是更新時一般是單個實體對象去操作。
IRepository.cs
// 省略其他...
// Update相關操作接口
Task UpdateAsync(T entity, CancellationToken cancellationToken = default);
RepositoryBase.cs
// 省略其他...
public async Task UpdateAsync(T entity, CancellationToken cancellationToken = default)
{
// 對於一般的更新而言,都是Attach到實體上的,只需要設置該實體的State為Modified就可以了
_dbContext.Entry(entity).State = EntityState.Modified;
await _dbContext.SaveChangesAsync(cancellationToken);
}
刪除實體(Delete)
對於刪除實體,可能會出現兩種情況:刪除一個實體;或者刪除一組實體。
IRepository.cs
// 省略其他...
// Delete相關操作接口,這里根據key刪除對象的接口需要用到一個獲取對象的方法
ValueTask<T?> GetAsync(object key);
Task DeleteAsync(object key);
Task DeleteAsync(T entity, CancellationToken cancellationToken = default);
Task DeleteRangeAsync(IEnumerable<T> entities, CancellationToken cancellationToken = default);
RepositoryBase.cs
// 省略其他...
public virtual ValueTask<T?> GetAsync(object key) => _dbContext.Set<T>().FindAsync(key);
public async Task DeleteAsync(object key)
{
var entity = await GetAsync(key);
if (entity is not null)
{
await DeleteAsync(entity);
}
}
public async Task DeleteAsync(T entity, CancellationToken cancellationToken = default)
{
_dbContext.Set<T>().Remove(entity);
await _dbContext.SaveChangesAsync(cancellationToken);
}
public async Task DeleteRangeAsync(IEnumerable<T> entities, CancellationToken cancellationToken = default)
{
_dbContext.Set<T>().RemoveRange(entities);
await _dbContext.SaveChangesAsync(cancellationToken);
}
獲取實體(Retrieve)
對於如何獲取實體,是最復雜的一部分。我們不僅要考慮通過什么方式獲取哪些數據,還需要考慮獲取的數據有沒有特殊的要求比如排序、分頁、數據對象類型的轉換之類的問題。
具體來說,比如下面這一個典型的LINQ
查詢語句:
var results = await _context.A.Join(_context.B, a => a.Id, b => b.aId, (a, b) => new
{
// ...
})
.Where(ab => ab.Name == "name" && ab.Date == DateTime.Now)
.Select(ab => new
{
// ...
})
.OrderBy(o => o.Date)
.Skip(20 * 1)
.Take(20)
.ToListAsync();
可以將整個查詢結構分割成以下幾個組成部分,而且每個部分基本都是以lambda表達式的方式表示的,這轉化成建模的話,可以使用Expression
相關的對象來表示:
- 查詢數據集准備過程,在這個過程中可能會出現
Include
/Join
/GroupJoin
/GroupBy
等等類似的關鍵字,它們的作用是構建一個用於接下來將要進行查詢的數據集。 Where
子句,用於過濾查詢集合。Select
子句,用於轉換原始數據類型到我們想要的結果類型。Order
子句,用於對結果集進行排序,這里可能會包含類似:OrderBy/OrderByDescending/ThenBy/ThenByDescending
等關鍵字。Paging
子句,用於對結果集進行后端分頁返回,一般都是Skip/Take
一起使用。- 其他子句,多數是條件控制,比如
AsNoTracking
/SplitQuery
等等。
為了保持我們的演示不會過於復雜,我會做一些取舍。在這里的實現我參考了Edi.Wang的Moonglade中的相關實現。有興趣的小伙伴也可以去找一下一個更完整的實現:Ardalis.Specification。
首先來定義一個簡單的ISpecification
來表示查詢的各類條件:
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query;
namespace TodoList.Application.Common.Interfaces;
public interface ISpecification<T>
{
// 查詢條件子句
Expression<Func<T, bool>> Criteria { get; }
// Include子句
Func<IQueryable<T>, IIncludableQueryable<T, object>> Include { get; }
// OrderBy子句
Expression<Func<T, object>> OrderBy { get; }
// OrderByDescending子句
Expression<Func<T, object>> OrderByDescending { get; }
// 分頁相關屬性
int Take { get; }
int Skip { get; }
bool IsPagingEnabled { get; }
}
並實現這個泛型接口,放在Application/Common
中:
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query;
using TodoList.Application.Common.Interfaces;
namespace TodoList.Application.Common;
public abstract class SpecificationBase<T> : ISpecification<T>
{
protected SpecificationBase() { }
protected SpecificationBase(Expression<Func<T, bool>> criteria) => Criteria = criteria;
public Expression<Func<T, bool>> Criteria { get; private set; }
public Func<IQueryable<T>, IIncludableQueryable<T, object>> Include { get; private set; }
public List<string> IncludeStrings { get; } = new();
public Expression<Func<T, object>> OrderBy { get; private set; }
public Expression<Func<T, object>> OrderByDescending { get; private set; }
public int Take { get; private set; }
public int Skip { get; private set; }
public bool IsPagingEnabled { get; private set; }
public void AddCriteria(Expression<Func<T, bool>> criteria) => Criteria = Criteria is not null ? Criteria.AndAlso(criteria) : criteria;
protected virtual void AddInclude(Func<IQueryable<T>, IIncludableQueryable<T, object>> includeExpression) => Include = includeExpression;
protected virtual void AddInclude(string includeString) => IncludeStrings.Add(includeString);
protected virtual void ApplyPaging(int skip, int take)
{
Skip = skip;
Take = take;
IsPagingEnabled = true;
}
protected virtual void ApplyOrderBy(Expression<Func<T, object>> orderByExpression) => OrderBy = orderByExpression;
protected virtual void ApplyOrderByDescending(Expression<Func<T, object>> orderByDescendingExpression) => OrderByDescending = orderByDescendingExpression;
}
// https://stackoverflow.com/questions/457316/combining-two-expressions-expressionfunct-bool
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var parameter = Expression.Parameter(typeof(T));
var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
var left = leftVisitor.Visit(expr1.Body);
var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
var right = rightVisitor.Visit(expr2.Body);
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(left ?? throw new InvalidOperationException(),
right ?? throw new InvalidOperationException()), parameter);
}
private class ReplaceExpressionVisitor : ExpressionVisitor
{
private readonly Expression _oldValue;
private readonly Expression _newValue;
public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
{
_oldValue = oldValue;
_newValue = newValue;
}
public override Expression Visit(Expression node) => node == _oldValue ? _newValue : base.Visit(node);
}
}
為了在RepositoryBase
中能夠把所有的Spcification串起來形成查詢子句,我們還需要定義一個用於組織Specification的SpecificationEvaluator
類:
using TodoList.Application.Common.Interfaces;
namespace TodoList.Application.Common;
public class SpecificationEvaluator<T> where T : class
{
public static IQueryable<T> GetQuery(IQueryable<T> inputQuery, ISpecification<T>? specification)
{
var query = inputQuery;
if (specification?.Criteria is not null)
{
query = query.Where(specification.Criteria);
}
if (specification?.Include is not null)
{
query = specification.Include(query);
}
if (specification?.OrderBy is not null)
{
query = query.OrderBy(specification.OrderBy);
}
else if (specification?.OrderByDescending is not null)
{
query = query.OrderByDescending(specification.OrderByDescending);
}
if (specification?.IsPagingEnabled != false)
{
query = query.Skip(specification!.Skip).Take(specification.Take);
}
return query;
}
}
在IRepository
中添加查詢相關的接口,大致可以分為以下這幾類接口,每類中又可能存在同步接口和異步接口:
IRepository.cs
// 省略其他...
// 1. 查詢基礎操作接口
IQueryable<T> GetAsQueryable();
IQueryable<T> GetAsQueryable(ISpecification<T> spec);
// 2. 查詢數量相關接口
int Count(ISpecification<T>? spec = null);
int Count(Expression<Func<T, bool>> condition);
Task<int> CountAsync(ISpecification<T>? spec);
// 3. 查詢存在性相關接口
bool Any(ISpecification<T>? spec);
bool Any(Expression<Func<T, bool>>? condition = null);
// 4. 根據條件獲取原始實體類型數據相關接口
Task<T?> GetAsync(Expression<Func<T, bool>> condition);
Task<IReadOnlyList<T>> GetAsync();
Task<IReadOnlyList<T>> GetAsync(ISpecification<T>? spec);
// 5. 根據條件獲取映射實體類型數據相關接口,涉及到Group相關操作也在其中,使用selector來傳入映射的表達式
TResult? SelectFirstOrDefault<TResult>(ISpecification<T>? spec, Expression<Func<T, TResult>> selector);
Task<TResult?> SelectFirstOrDefaultAsync<TResult>(ISpecification<T>? spec, Expression<Func<T, TResult>> selector);
Task<IReadOnlyList<TResult>> SelectAsync<TResult>(Expression<Func<T, TResult>> selector);
Task<IReadOnlyList<TResult>> SelectAsync<TResult>(ISpecification<T>? spec, Expression<Func<T, TResult>> selector);
Task<IReadOnlyList<TResult>> SelectAsync<TGroup, TResult>(Expression<Func<T, TGroup>> groupExpression, Expression<Func<IGrouping<TGroup, T>, TResult>> selector, ISpecification<T>? spec = null);
有了這些基礎,我們就可以去Infrastructure/Persistence/Repositories
中實現RepositoryBase
類剩下的關於查詢部分的代碼了:
RepositoryBase.cs
// 省略其他...
// 1. 查詢基礎操作接口實現
public IQueryable<T> GetAsQueryable()
=> _dbContext.Set<T>();
public IQueryable<T> GetAsQueryable(ISpecification<T> spec)
=> ApplySpecification(spec);
// 2. 查詢數量相關接口實現
public int Count(Expression<Func<T, bool>> condition)
=> _dbContext.Set<T>().Count(condition);
public int Count(ISpecification<T>? spec = null)
=> null != spec ? ApplySpecification(spec).Count() : _dbContext.Set<T>().Count();
public Task<int> CountAsync(ISpecification<T>? spec)
=> ApplySpecification(spec).CountAsync();
// 3. 查詢存在性相關接口實現
public bool Any(ISpecification<T>? spec)
=> ApplySpecification(spec).Any();
public bool Any(Expression<Func<T, bool>>? condition = null)
=> null != condition ? _dbContext.Set<T>().Any(condition) : _dbContext.Set<T>().Any();
// 4. 根據條件獲取原始實體類型數據相關接口實現
public async Task<T?> GetAsync(Expression<Func<T, bool>> condition)
=> await _dbContext.Set<T>().FirstOrDefaultAsync(condition);
public async Task<IReadOnlyList<T>> GetAsync()
=> await _dbContext.Set<T>().AsNoTracking().ToListAsync();
public async Task<IReadOnlyList<T>> GetAsync(ISpecification<T>? spec)
=> await ApplySpecification(spec).AsNoTracking().ToListAsync();
// 5. 根據條件獲取映射實體類型數據相關接口實現
public TResult? SelectFirstOrDefault<TResult>(ISpecification<T>? spec, Expression<Func<T, TResult>> selector)
=> ApplySpecification(spec).AsNoTracking().Select(selector).FirstOrDefault();
public Task<TResult?> SelectFirstOrDefaultAsync<TResult>(ISpecification<T>? spec, Expression<Func<T, TResult>> selector)
=> ApplySpecification(spec).AsNoTracking().Select(selector).FirstOrDefaultAsync();
public async Task<IReadOnlyList<TResult>> SelectAsync<TResult>(Expression<Func<T, TResult>> selector)
=> await _dbContext.Set<T>().AsNoTracking().Select(selector).ToListAsync();
public async Task<IReadOnlyList<TResult>> SelectAsync<TResult>(ISpecification<T>? spec, Expression<Func<T, TResult>> selector)
=> await ApplySpecification(spec).AsNoTracking().Select(selector).ToListAsync();
public async Task<IReadOnlyList<TResult>> SelectAsync<TGroup, TResult>(
Expression<Func<T, TGroup>> groupExpression,
Expression<Func<IGrouping<TGroup, T>, TResult>> selector,
ISpecification<T>? spec = null)
=> null != spec ?
await ApplySpecification(spec).AsNoTracking().GroupBy(groupExpression).Select(selector).ToListAsync() :
await _dbContext.Set<T>().AsNoTracking().GroupBy(groupExpression).Select(selector).ToListAsync();
// 用於拼接所有Specification的輔助方法,接收一個`IQuerybale<T>對象(通常是數據集合)
// 和一個當前實體定義的Specification對象,並返回一個`IQueryable<T>`對象為子句執行后的結果。
private IQueryable<T> ApplySpecification(ISpecification<T>? spec)
=> SpecificationEvaluator<T>.GetQuery(_dbContext.Set<T>().AsQueryable(), spec);
引入使用
為了驗證通用Repsitory的用法,我們可以先在Infrastructure/DependencyInjection.cs
中進行依賴注入:
// in AddInfrastructure, 省略其他
services.AddScoped(typeof(IRepository<>), typeof(RepositoryBase<>));
驗證
用於初步驗證(主要是查詢接口),我們在Application
項目里新建文件夾TodoItems/Specs
,創建一個TodoItemSpec
類:
TodoItemSpec.cs
using TodoList.Application.Common;
using TodoList.Domain.Entities;
using TodoList.Domain.Enums;
namespace TodoList.Application.TodoItems.Specs;
public sealed class TodoItemSpec : SpecificationBase<TodoItem>
{
public TodoItemSpec(bool done, PriorityLevel priority) : base(t => t.Done == done && t.Priority == priority)
{
}
}
然后我們臨時使用示例接口WeatherForecastController
,通過日志來看一下查詢的正確性。
private readonly IRepository<TodoItem> _repository;
private readonly ILogger<WeatherForecastController> _logger;
// 為了驗證,臨時在這注入IRepository<TodoItem>對象,驗證完后撤銷修改
public WeatherForecastController(IRepository<TodoItem> repository, ILogger<WeatherForecastController> logger)
{
_repository = repository;
_logger = logger;
}
在Get
方法里增加這段邏輯用於觀察日志輸出:
// 記錄日志
_logger.LogInformation($"maybe this log is provided by Serilog...");
var spec = new TodoItemSpec(true, PriorityLevel.High);
var items = _repository.GetAsync(spec).Result;
foreach (var item in items)
{
_logger.LogInformation($"item: {item.Id} - {item.Title} - {item.Priority}");
}
啟動Api
項目然后請求示例接口,觀察控制台輸出:
# 以上省略,Controller日志開始...
[16:49:59 INF] maybe this log is provided by Serilog...
[16:49:59 INF] Entity Framework Core 6.0.1 initialized 'TodoListDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.1' with options: MigrationsAssembly=TodoList.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
[16:49:59 INF] Executed DbCommand (51ms) [Parameters=[@__done_0='?' (DbType = Boolean), @__priority_1='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
SELECT [t].[Id], [t].[Created], [t].[CreatedBy], [t].[Done], [t].[LastModified], [t].[LastModifiedBy], [t].[ListId], [t].[Priority], [t].[Title]
FROM [TodoItems] AS [t]
WHERE ([t].[Done] = @__done_0) AND ([t].[Priority] = @__priority_1)
# 下面這句是我們之前初始化數據庫的種子數據,可以參考上一篇文章結尾的驗證截圖。
[16:49:59 INF] item: 87f1ddf1-e6cd-4113-74ed-08d9c5112f6b - Apples - High
[16:49:59 INF] Executing ObjectResult, writing value of type 'TodoList.Api.WeatherForecast[]'.
[16:49:59 INF] Executed action TodoList.Api.Controllers.WeatherForecastController.Get (TodoList.Api) in 160.5517ms
總結
在本文中,我大致演示了實現一個通用Repository
基礎框架的過程。實際上關於Repository
的組織與實現有很多種實現方法,每個人的關注點和思路都會有不同,但是大的方向基本都是這樣,無非是抽象的粒度和提供的接口的方便程度不同。有興趣的像伙伴可以仔細研究一下參考資料里的第2個實現,也可以從Nuget直接下載在項目中引用使用。
感謝大家耐心看完。從下一篇文章開始,我們就進入喜聞樂見的CRUD環節。