实现代码
1、新建接口类:IRepository.cs,规范各个操作类的都有那些方法,方便管理。
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace CMS.Entity.Interfaces { public interface IRepositorywhere T:class { /// /// 添加 /// /// 实体对象 void Add(T entity); /// /// 更新 /// /// 实体对象 void Update(T entity); /// /// 删除 /// /// 实体对象 void Delete(T entity); /// /// 删除 /// /// 条件(lambda表达式) void Delete(Expression bool>> where); /// /// 根据ID获取一个对象 /// /// 主键ID /// 对象 T GetById(long Id); /// /// 根据ID获取一个对象 /// /// 主键ID /// 对象 T GetById(string Id); /// /// 根据条件获取一个对象 /// /// 条件(lambda表达式) /// 对象 T Get(Expression bool>> where); /// /// 获取所有数据 /// /// 所有数据 IQueryable GetAll(); /// /// 根据条件获取数据 /// /// 条件(lambda表达式) /// 数据 IQueryable GetMany(Expression bool>> where); /// /// 根据条件获取记录数 /// /// 条件(lambda表达式) /// int GetCount(Expression bool>> where); /// /// 关闭代理 /// void CloseProxy(); /// /// 打开代理 /// void OpenProxy(); /// /// 是否有指定条件的元素 /// /// 条件(lambda表达式) /// bool IsHasValue(Expression bool>> where); } }
2、新建仓储基础操作类RepositoryBase.cs,注意要一一对应实现IRepositroy接口的方法
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace CMS.Entity.Interfaces { public abstract class BaseRepositorywhere T: class { private BcmfDBContext db;//数据库上下文 public BaseRepository(BcmfDBContext _db) { db = _db; } public virtual void Save() { db.SaveChanges(); } public virtual void Add(T entity) { db.Set ().Add(entity); } public virtual void CloseProxy() { db.Database.CommitTransaction(); } public virtual void Delete(T entity) { db.Set ().Remove(entity); } public virtual void Delete(System.Linq.Expressions.Expression bool>> where) { var dataList = db.Set ().Where(where).AsEnumerable(); db.Set ().RemoveRange(dataList); } public virtual T Get(System.Linq.Expressions.Expression bool>> where) { return db.Set ().FirstOrDefault(where); } public virtual System.Linq.IQueryable GetAll() { return db.Set (); } public virtual T GetById(long Id) { return db.Set ().Find(Id); } public virtual T GetById(string Id) { return db.Set ().Find(Id); } public virtual int GetCount(System.Linq.Expressions.Expression bool>> where) { return db.Set ().Count(where); } public virtual System.Linq.IQueryable GetMany(System.Linq.Expressions.Expression bool>> where) { return db.Set ().Where(where); } public virtual bool IsHasValue(System.Linq.Expressions.Expression bool>> where) { return db.Set ().Any(where); } public virtual void OpenProxy() { db.Database.BeginTransaction(); } public virtual void Update(T entity) { db.Set ().Attach(entity); db.Entry (entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified; } } }
3、新建仓储类TUserRepository与TOperateLogRepository,TUserRepository用于操作用户表,TOperateLogRepository用于操作用户记录表,对应的User类与OperateLog类根据项目需求自行创建
using System; using System.Collections.Generic; using System.Text; using CMS.Entity.Repository; using CMS.Entity.Entity; using Microsoft.EntityFrameworkCore; using System.Linq; using CMS.Entity.Interfaces; namespace CMS.Entity.Repository { public class TUserRepository :BaseRepository,IUserRepository { public TUserRepository(BcmfDBContext db) : base(db) { } } public interface IUserRepository : IRepository { } }
using System; using System.Collections.Generic; using System.Text; using CMS.Entity.Repository; using CMS.Entity.Entity; using Microsoft.EntityFrameworkCore; using System.Linq; using CMS.Entity.Interfaces; namespace CMS.Entity.Repository { public class TOperateLogRepository : BaseRepository, IOperateLogRepository { public TOperateLogRepository(BcmfDBContext db) : base(db) { } } public interface IOperateLogRepository : IRepository { } }
4、分别在UserController与OperateLogController控制器中的构造函数注入仓储类
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using CMS.Entity; using CMS.Entity.Entity; using Newtonsoft.Json; using CMS.WebApi.Core; using Microsoft.EntityFrameworkCore.Query; using CMS.Entity.Repository; namespace CMS.WebApi.Controllers { ////// 用户中心 /// //[Produces("application/json")] [Route("api/[controller]")] [ApiController] public class UsersController : ControllerBase { private readonly IUserRepository userRepository; public UsersController(IUserRepository _userRepository) { userRepository = _userRepository; } /// /// 获取用户列表 /// /// [HttpGet] public string Get() { var userList= userRepository.GetAll().ToList(); return JsonConvert.SerializeObject(userList); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using CMS.Entity.Repository; using Newtonsoft.Json; namespace CMS.WebApi.Controllers { [Route("api/[controller]")] [ApiController] public class OperateLogController : ControllerBase { private readonly IOperateLogRepository operateLogRepository; public OperateLogController(IOperateLogRepository _operateLogRepository) { operateLogRepository = _operateLogRepository; } [HttpGet] public string Get() { var result = operateLogRepository.GetMany(m=>m.ActionLogId<100); return JsonConvert.SerializeObject(result); } } }
5、完成上述操作后,运行获取数据时会系统报错,那是由于还没将仓储类注入到服务中,接下来就实现用AutoFac注入仓储类到项目服务中
添加引用Autofac,Auto.Configuration,Autofac.Extensions.DependencyInjection到项目中
这里贴出Nuget程序控制台命令:
Install-Package Autofac -Version 4.9.2
Install-Package Autofac.Configuration -Version 4.1.0
Install-Package Autofac.Extensions.DependencyInjection -Version 4.4.0
6、打开项目Startup.cs,找到ConfigureServices方法,将void改为IServiceProvider返回值,如下
//先引用命名空间
using Autofac;
using Autofac.Extensions.DependencyInjection;
public IServiceProvider ConfigureServices(IServiceCollection services) { ... ////批量匹配注入,使用AutoFac提供的容器接管当前项目默认容器 var builder = new ContainerBuilder(); //注入entity层的repository类builder.RegisterType(typeof(TUserRepository)).As(typeof(IUserRepository)).InstancePerDependency(); //批量注入Repository的类 builder.RegisterAssemblyTypes(typeof(TUserRepository).Assembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces(); builder.Populate(services); var container = builder.Build(); //ConfigureServices方法由void改为返回IServiceProvider return new AutofacServiceProvider(container); }
7、重新生成发布项目,完成