仓储模式究竟算不算是一种反模式现象?

摘要:前言 仓储模式我们已耳熟能详,但当我们将其进行应用时,真的是那么得心应手吗?确定是解放了生产力吗?这到底是怎样的一个存在,确定不是反模式?,一篇详文我们探讨仓储模式,这里仅我个人的思考,若有更深刻的理解,请在评论中给出 仓储反模式 5年前我
前言 仓储模式我们已耳熟能详,但当我们将其进行应用时,真的是那么得心应手吗?确定是解放了生产力吗?这到底是怎样的一个存在,确定不是反模式?,一篇详文我们探讨仓储模式,这里仅我个人的思考,若有更深刻的理解,请在评论中给出 仓储反模式 5年前我在Web APi中使用EntityFramework中写了一个仓储模式,并将其放在我个人github上,此种模式也完全是参考所流行的网传模式,现如今在我看来那是极其错误的仓储模式形式,当时在EntityFramework中有IDbSet接口,然后我们又定义一个IDbContext接口等等,大同小异,接下来我们看看在.NET Core中大多是如何使用的呢? 定义通用IRepository接口 public interface IRepository<TEntity> where TEntity : class { /// <summary> /// 通过id获得实体 /// </summary> /// <param name="id"></param> /// <returns></returns> TEntity GetById(object id); //其他诸如修改、删除、查询接口 } 当然还有泛型类可能需要基础子基础类等等,这里我们一并忽略 定义EntityRepository实现IRepository接口 public abstract class EntityRepository<TEntity> : IRepository<TEntity> where TEntity : class { private readonly DbContext _context; public EntityRepository(DbContext context) { _context = context; } /// <summary> /// 通过id获取实体 /// </summary> /// <param name="id"></param> /// <returns></returns> public TEntity GetById(object id) { return _context.Set<TEntity>().Find(id); } } 定义业务仓储接口IUserRepository接口 public interface IUserRepository : IRepository<User> { /// <summary> /// 其他非通用接口 /// </summary> /// <returns></returns> List<User> Other(); } 定义业务仓储接口具体实现UserRepository public class UserRepository : EntityRepository<User>, IUserRepository { public List<User> Other() { throw new NotImplementedException(); } } 我们定义基础通用接口和实现,然后每一个业务都定义一个仓储接口和实现,最后将其进行注入,如下: services.AddDbContext<EFCoreDbContext>(options => { options.UseSqlServer(@"Server=.;Database=EFCore;Trusted_Connection=True;"); }); services.AddScoped(typeof(IRepository<>), typeof(EntityRepository<>)); services.AddScoped<IUserRepository, UserRepository>(); 有一部分童鞋在项目中可能就是使用如上方式,每一个具体仓储实现我们将其看成传统的数据访问层,紧接着我们还定
阅读全文