ASP.NETCore使用AutoFac依赖注入
实现代码
1、新建接口类:IRepository.cs,规范各个操作类的都有那些方法,方便管理。
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Linq.Expressions;usingSystem.Text;namespaceCMS.Entity.Interfaces{publicinterfaceIRepository<T>whereT:class{///<summary>///添加///</summary>///<paramname="entity">实体对象</param>voidAdd(Tentity);///<summary>///更新///</summary>///<paramname="entity">实体对象</param>voidUpdate(Tentity);///<summary>///删除///</summary>///<paramname="entity">实体对象</param>voidDelete(Tentity);///<summary>///删除///</summary>///<paramname="where">条件(lambda表达式)</param>voidDelete(Expression<Func<T,bool>>where);///<summary>///根据ID获取一个对象///</summary>///<paramname="Id">主键ID</param>///<returns>对象</returns>TGetById(longId);///<summary>///根据ID获取一个对象///</summary>///<paramname="Id">主键ID</param>///<returns>对象</returns>TGetById(stringId);///<summary>///根据条件获取一个对象///</summary>///<paramname="where">条件(lambda表达式)</param>///<returns>对象</returns>TGet(Expression<Func<T,bool>>where);///<summary>///获取所有数据///</summary>///<returns>所有数据</returns>IQueryable<T>GetAll();///<summary>///根据条件获取数据///</summary>///<paramname="where">条件(lambda表达式)</param>///<returns>数据</returns>IQueryable<T>GetMany(Expression<Func<T,bool>>where);///<summary>///根据条件获取记录数///</summary>///<paramname="where">条件(lambda表达式)</param>///<returns></returns>intGetCount(Expression<Func<T,bool>>where);///<summary>///关闭代理///</summary>voidCloseProxy();///<summary>///打开代理///</summary>voidOpenProxy();///<summary>///是否有指定条件的元素///</summary>///<paramname="where">条件(lambda表达式)</param>///<returns></returns>boolIsHasValue(Expression<Func<T,bool>>where);}}
2、新建仓储基础操作类RepositoryBase.cs,注意要一一对应实现IRepositroy接口的方法
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Linq;namespaceCMS.Entity.Interfaces{publicabstractclassBaseRepository<T>whereT:class{privateBcmfDBContextdb;//数据库上下文publicBaseRepository(BcmfDBContext_db){db=_db;}publicvirtualvoidSave(){db.SaveChanges();}publicvirtualvoidAdd(Tentity){db.Set<T>().Add(entity);}publicvirtualvoidCloseProxy(){db.Database.CommitTransaction();}publicvirtualvoidDelete(Tentity){db.Set<T>().Remove(entity);}publicvirtualvoidDelete(System.Linq.Expressions.Expression<Func<T,bool>>where){vardataList=db.Set<T>().Where(where).AsEnumerable();db.Set<T>().RemoveRange(dataList);}publicvirtualTGet(System.Linq.Expressions.Expression<Func<T,bool>>where){returndb.Set<T>().FirstOrDefault(where);}publicvirtualSystem.Linq.IQueryable<T>GetAll(){returndb.Set<T>();}publicvirtualTGetById(longId){returndb.Set<T>().Find(Id);}publicvirtualTGetById(stringId){returndb.Set<T>().Find(Id);}publicvirtualintGetCount(System.Linq.Expressions.Expression<Func<T,bool>>where){returndb.Set<T>().Count(where);}publicvirtualSystem.Linq.IQueryable<T>GetMany(System.Linq.Expressions.Expression<Func<T,bool>>where){returndb.Set<T>().Where(where);}publicvirtualboolIsHasValue(System.Linq.Expressions.Expression<Func<T,bool>>where){returndb.Set<T>().Any(where);}publicvirtualvoidOpenProxy(){db.Database.BeginTransaction();}publicvirtualvoidUpdate(Tentity){db.Set<T>().Attach(entity);db.Entry<T>(entity).State=Microsoft.EntityFrameworkCore.EntityState.Modified;}}}
3、新建仓储类TUserRepository与TOperateLogRepository,TUserRepository用于操作用户表,TOperateLogRepository用于操作用户记录表,对应的User类与OperateLog类根据项目需求自行创建
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingCMS.Entity.Repository;usingCMS.Entity.Entity;usingMicrosoft.EntityFrameworkCore;usingSystem.Linq;usingCMS.Entity.Interfaces;namespaceCMS.Entity.Repository{publicclassTUserRepository:BaseRepository<User>,IUserRepository{publicTUserRepository(BcmfDBContextdb):base(db){}}publicinterfaceIUserRepository:IRepository<User>{}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingCMS.Entity.Repository;usingCMS.Entity.Entity;usingMicrosoft.EntityFrameworkCore;usingSystem.Linq;usingCMS.Entity.Interfaces;namespaceCMS.Entity.Repository{publicclassTOperateLogRepository:BaseRepository<OperateLog>,IOperateLogRepository{publicTOperateLogRepository(BcmfDBContextdb):base(db){}}publicinterfaceIOperateLogRepository:IRepository<OperateLog>{}}
4、分别在UserController与OperateLogController控制器中的构造函数注入仓储类
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingCMS.Entity;usingCMS.Entity.Entity;usingNewtonsoft.Json;usingCMS.WebApi.Core;usingMicrosoft.EntityFrameworkCore.Query;usingCMS.Entity.Repository;namespaceCMS.WebApi.Controllers{///<summary>///用户中心///</summary>//[Produces("application/json")][Route("api/[controller]")][ApiController]publicclassUsersController:ControllerBase{privatereadonlyIUserRepositoryuserRepository;publicUsersController(IUserRepository_userRepository){userRepository=_userRepository;}///<summary>///获取用户列表///</summary>///<returns></returns>[HttpGet]publicstringGet(){varuserList=userRepository.GetAll().ToList();returnJsonConvert.SerializeObject(userList);}}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingCMS.Entity.Repository;usingNewtonsoft.Json;namespaceCMS.WebApi.Controllers{[Route("api/[controller]")][ApiController]publicclassOperateLogController:ControllerBase{privatereadonlyIOperateLogRepositoryoperateLogRepository;publicOperateLogController(IOperateLogRepository_operateLogRepository){operateLogRepository=_operateLogRepository;}[HttpGet]publicstringGet(){varresult=operateLogRepository.GetMany(m=>m.ActionLogId<100);returnJsonConvert.SerializeObject(result);}}}
5、完成上述操作后,运行获取数据时会系统报错,那是由于还没将仓储类注入到服务中,接下来就实现用AutoFac注入仓储类到项目服务中
添加引用Autofac,Auto.Configuration,Autofac.Extensions.DependencyInjection到项目中
这里贴出Nuget程序控制台命令:
Install-PackageAutofac-Version4.9.2
Install-PackageAutofac.Configuration-Version4.1.0
Install-PackageAutofac.Extensions.DependencyInjection-Version4.4.0
6、打开项目Startup.cs,找到ConfigureServices方法,将void改为IServiceProvider返回值,如下
//先引用命名空间usingAutofac;usingAutofac.Extensions.DependencyInjection;builder= builder.RegisterAssemblyTypes(=>t.Name.EndsWith(container=
7、重新生成发布项目,完成
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。