ASP.NETCore使用AutoFac依赖注入
程序员文章站
2022-03-20 10:21:26
实现代码 1、新建接口类:IRepository.cs,规范各个操作类的都有那些方法,方便管理。 2、新建仓储基础操作类RepositoryBase.cs,注意要一一对应实现IRepositroy接口的方法 3、新建仓储类TUserRepository与TOperateLogRepository,T ......
实现代码
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 irepository<t> where t:class { /// <summary> /// 添加 /// </summary> /// <param name="entity">实体对象</param> void add(t entity); /// <summary> /// 更新 /// </summary> /// <param name="entity">实体对象</param> void update(t entity); /// <summary> /// 删除 /// </summary> /// <param name="entity">实体对象</param> void delete(t entity); /// <summary> /// 删除 /// </summary> /// <param name="where">条件(lambda表达式)</param> void delete(expression<func<t, bool>> where); /// <summary> /// 根据id获取一个对象 /// </summary> /// <param name="id">主键id</param> /// <returns>对象</returns> t getbyid(long id); /// <summary> /// 根据id获取一个对象 /// </summary> /// <param name="id">主键id</param> /// <returns>对象</returns> t getbyid(string id); /// <summary> /// 根据条件获取一个对象 /// </summary> /// <param name="where">条件(lambda表达式)</param> /// <returns>对象</returns> t get(expression<func<t, bool>> where); /// <summary> /// 获取所有数据 /// </summary> /// <returns>所有数据</returns> iqueryable<t> getall(); /// <summary> /// 根据条件获取数据 /// </summary> /// <param name="where">条件(lambda表达式)</param> /// <returns>数据</returns> iqueryable<t> getmany(expression<func<t, bool>> where); /// <summary> /// 根据条件获取记录数 /// </summary> /// <param name="where">条件(lambda表达式)</param> /// <returns></returns> int getcount(expression<func<t, bool>> where); /// <summary> /// 关闭代理 /// </summary> void closeproxy(); /// <summary> /// 打开代理 /// </summary> void openproxy(); /// <summary> /// 是否有指定条件的元素 /// </summary> /// <param name="where">条件(lambda表达式)</param> /// <returns></returns> bool ishasvalue(expression<func<t, 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 baserepository<t> where 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<t>().add(entity); } public virtual void closeproxy() { db.database.committransaction(); } public virtual void delete(t entity) { db.set<t>().remove(entity); } public virtual void delete(system.linq.expressions.expression<func<t, bool>> where) { var datalist = db.set<t>().where(where).asenumerable(); db.set<t>().removerange(datalist); } public virtual t get(system.linq.expressions.expression<func<t, bool>> where) { return db.set<t>().firstordefault(where); } public virtual system.linq.iqueryable<t> getall() { return db.set<t>(); } public virtual t getbyid(long id) { return db.set<t>().find(id); } public virtual t getbyid(string id) { return db.set<t>().find(id); } public virtual int getcount(system.linq.expressions.expression<func<t, bool>> where) { return db.set<t>().count(where); } public virtual system.linq.iqueryable<t> getmany(system.linq.expressions.expression<func<t, bool>> where) { return db.set<t>().where(where); } public virtual bool ishasvalue(system.linq.expressions.expression<func<t, bool>> where) { return db.set<t>().any(where); } public virtual void openproxy() { db.database.begintransaction(); } public virtual void update(t entity) { db.set<t>().attach(entity); db.entry<t>(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<user>,iuserrepository { public tuserrepository(bcmfdbcontext db) : base(db) { } } public interface iuserrepository : irepository<user> { } }
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<operatelog>, ioperatelogrepository { public toperatelogrepository(bcmfdbcontext db) : base(db) { } } public interface ioperatelogrepository : irepository<operatelog> { } }
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 { /// <summary> /// 用户中心 /// </summary> //[produces("application/json")] [route("api/[controller]")] [apicontroller] public class userscontroller : controllerbase { private readonly iuserrepository userrepository; public userscontroller(iuserrepository _userrepository) { userrepository = _userrepository; } /// <summary> /// 获取用户列表 /// </summary> /// <returns></returns> [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、重新生成发布项目,完成
上一篇: 我俩顶住,你俩快钻出去
下一篇: java配置环境及安装
推荐阅读
-
webapi中如何使用依赖注入
-
ASP.NET MVC IOC依赖注入之Autofac系列开篇
-
netcore 2.2 使用 Autofac 实现自动注入
-
ASP.NETCore 3.0 Autofac替换及控制器属性注入及全局容器使用
-
C#控制台程序中使用官方依赖注入的实现
-
Spring quartz Job依赖注入使用详解
-
AngularJS的依赖注入实例分析(使用module和injector)
-
net core WebApi——依赖注入Autofac
-
ASP.NET Core 2.2 WebApi 系列【三】AutoFac 仓储接口的依赖注入
-
.net core控制台程序中使用原生依赖注入