ASP.NETCore使用AutoFac依赖注入
实现代码
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<);
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、重新生成发布项目,完成
ASP.NETCore使用AutoFac依赖注入的更多相关文章
- ASP.NET MVC Autofac依赖注入的一点小心得(包含特性注入)
前言 IOC的重要性 大家都清楚..便利也都知道..新的ASP.NET Core也大量使用了这种手法.. 一直憋着没写ASP.NET Core的文章..还是怕误导大家.. 今天这篇也不是讲Core的 ...
- ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下
ADO.NET 一.ADO.NET概要 ADO.NET是.NET框架中的重要组件,主要用于完成C#应用程序访问数据库 二.ADO.NET的组成 ①System.Data → DataTable, ...
- ASP.NET MVC IOC依赖注入之Autofac系列(二)- WebForm当中应用
上一章主要介绍了Autofac在MVC当中的具体应用,本章将继续简单的介绍下Autofac在普通的WebForm当中的使用. PS:目前本人还不知道WebForm页面的构造函数要如何注入,以下在Web ...
- ASP.NET MVC IOC依赖注入之Autofac系列(一)- MVC当中应用
话不多说,直入主题看我们的解决方案结构: 分别对上面的工程进行简单的说明: 1.TianYa.DotNetShare.Model:为demo的实体层 2.TianYa.DotNetShare.Repo ...
- asp.net mvc4 简单使用Autofac依赖注入小结
1,首先使用 NuGet下载适当的Autofac版本 文件一,Autofac.3.5.2 文件二,Autofac.Mvc4.3.1.0 1,接口类 public interface IReposito ...
- 【干货】利用MVC5+EF6搭建博客系统(二)测试添加数据、集成Autofac依赖注入
PS:如果图片模糊,鼠标右击复制图片网址,然后在浏览器中打开即可. 一.测试仓储层.业务层是否能实现对数据库表的操作 1.在52MVCBlog.IRepository程序集下创建IsysUserInf ...
- 几十行代码实现ASP.NET Core自动依赖注入
在开发.NET Core web服务的时候,我们习惯使用自带的依赖注入容器来进行注入. 于是就会经常进行一个很频繁的的重复动作:定义一个接口->写实现类->注入 有时候会忘了写Add这一步 ...
- Autofac 依赖注入小知识
Autofac 依赖注入小知识 控制反转/依赖注入 IOC/DI 依赖接口而不依赖于实现,是面向对象的六大设计原则(SOLID)之一.即依赖倒置原则(Dependence Inversion Prin ...
- 从零开始,搭建博客系统MVC5+EF6搭建框架(2),测试添加数据、集成Autofac依赖注入
一.测试仓储层.业务层是否能实现对数据库表的操作 1.创建IsysUserInfoRepository接口来继承IBaseRepository父接口 namespace Wchl.WMBlog.IRe ...
随机推荐
- Bzoj 1055: [HAOI2008]玩具取名 (区间DP)
Bzoj 1055: [HAOI2008]玩具取名 (区间DP) 题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1055 区间动态规划和可 ...
- UVa-1368-DNA序列
这题的话,我们每次统计的话,是以列为外层循环,以行为内层循环,逐一按列进行比较. 统计完了之后,题目中要求说到要hamming值最小的,那我们就选用该列最多的字母就可以了,如果有数目相等的字母,那就按 ...
- [LUOGU] P4767 [IOI2000]邮局
https://www.luogu.org/problemnew/show/P4767 四边形不等式好题! 可以设f[i][j]表示前i个村庄,建了j个邮局的最小代价. 转移:f[i][j]=min{ ...
- 介绍几款移动的WebAPP框架
如果是 Angular 那就选 Ionic (一对好 CP)如果是 Vue 那就选 Vux (基于 WeUI)如果是 jQuery 那就选 Framework7 (iOS 和 Android 双皮肤) ...
- MySQL-简要说明
分类 安装发展顺序分为: 网状型数据库 层次型数据库 关系型数据库 面向对象数据库 主流:关系型数据库 关系型数据库 事务transaction: 多个操作被当作一个整体对待 • ACID: ...
- linux kernel如何处理大端小端字节序
(转)http://blog.csdn.net/skyflying2012/article/details/43771179 最近在做将kernel由小端处理器(arm)向大端处理器(ppc)的移植的 ...
- 分享读C Primer Plus时遇到的一个问题(补档5月7日)
最近在学习C Primer Plus.书中第66页,3.8 关键概念 这一小节中有这一段话: “计算机中的浮点数和整数在本质上不同,其存储方式和运算过程有很大区别.即使两个 32 位存储单元存储的位组 ...
- C#上位机开发(二)—— Hello,World
上一篇大致了解了一下单片机实际项目开发中上位机开发部分的内容以及VS下载与安装,按照编程惯例,接下来就是“Hello,World!” 1.新建C#项目工程 首先选择新建Windows窗体应用(.NET ...
- Android App性能自动化评测方法
前言 App运行在设备上的性能表现也是质量保障的一个重要环节.因此,当我们确保了基本功能的准确之后,还需要有一定的方法评测App在不同设备上的性能表现.本文将从性能指标,评测方法,自动化体系建设等三个 ...
- Matplotlib基本图形之饼状图
Matplotlib基本图形之饼状图 饼状图特点: 饼状图显示一个数据系列中各项大小与各项总和的比例饼状图的数据点显示为整个饼状图的百分比 示例代码 import os import time imp ...