前言

上一篇《一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](三)》,我们完成了:

* 引用SqlSugar

* 使用SqlSugar对Repository类的改造

并成功使用PostRepository来查询到了数据,今天我们来创建一个新的服务层以及安装配置依赖注入框架组件Autofac等。

本篇知识要点

* 创建服务层:TsBlog.Services
* 创建服务接口
* 实现服务接口
* 创建仓储接口
* 安装Autofac依赖注入组件
* 注册配置Autofac 依赖注入

教程内容

创建服务层

选中解决方案中的解决方案文件夹[1.Libraries],右键单击=>>添加=>>新项目,在弹出的对话框中添加一个.NET Framework 4.6.2的C#类库项目,命名为:TsBlog.Services。项目创建成功后,删除自动生成的Class1.cs文件。

由于服务层需要依赖于仓储层,所以首先切换到仓储层[TsBlog.Repositories]项目中,创建博文的仓储接口类:IPostRepository,代码如下:

using System.Collections.Generic;
using TsBlog.Domain.Entities; namespace TsBlog.Repositories
{
public interface IPostRepository
{
/// <summary>
/// 根据ID查询单条数据
/// </summary>
/// <param name="id">ID</param>
/// <returns></returns>
Post FindById(int id);
/// <summary>
/// 查询所有数据(无分页,大数量时请慎用)
/// </summary>
/// <returns></returns>
IEnumerable<Post> FindAll(); /// <summary>
/// 写入实体数据
/// </summary>
/// <param name="entity">博文实体类</param>
/// <returns></returns>
int Insert(Post entity); /// <summary>
/// 更新实体数据
/// </summary>
/// <param name="entity">博文实体类</param>
/// <returns></returns>
bool Update(Post entity); /// <summary>
/// 根据实体删除一条数据
/// </summary>
/// <param name="entity">博文实体类</param>
/// <returns></returns>
bool Delete(Post entity); /// <summary>
/// 删除指定ID的数据
/// </summary>
/// <param name="id">主键ID</param>
/// <returns></returns>
bool DeleteById(object id); /// <summary>
/// 删除指定ID集合的数据(批量删除)
/// </summary>
/// <param name="ids">主键ID集合</param>
/// <returns></returns>
bool DeleteByIds(object[] ids);
}
}

再切换到服务层,在刚才创建的服务层项目中首先引用仓储层,并分别创建以下服务接口和类文件:

IPostService.cs:

using System.Collections.Generic;
using TsBlog.Domain.Entities; namespace TsBlog.Services
{
public interface IPostService
{
/// <summary>
/// 根据ID查询单条数据
/// </summary>
/// <param name="id">ID</param>
/// <returns></returns>
Post FindById(int id);
/// <summary>
/// 查询所有数据(无分页,大数量时请慎用)
/// </summary>
/// <returns></returns>
IEnumerable<Post> FindAll(); /// <summary>
/// 写入实体数据
/// </summary>
/// <param name="entity">博文实体类</param>
/// <returns></returns>
int Insert(Post entity); /// <summary>
/// 更新实体数据
/// </summary>
/// <param name="entity">博文实体类</param>
/// <returns></returns>
bool Update(Post entity); /// <summary>
/// 根据实体删除一条数据
/// </summary>
/// <param name="entity">博文实体类</param>
/// <returns></returns>
bool Delete(Post entity); /// <summary>
/// 删除指定ID的数据
/// </summary>
/// <param name="id">主键ID</param>
/// <returns></returns>
bool DeleteById(object id); /// <summary>
/// 删除指定ID集合的数据(批量删除)
/// </summary>
/// <param name="ids">主键ID集合</param>
/// <returns></returns>
bool DeleteByIds(object[] ids);
}
}

PostService.cs

using System.Collections.Generic;
using TsBlog.Domain.Entities;
using TsBlog.Repositories; namespace TsBlog.Services
{
public class PostService : IPostService
{
private readonly IPostRepository _postRepository;
public PostService(IPostRepository postRepository)
{
_postRepository = postRepository;
}
public bool Delete(Post entity)
{
return _postRepository.Delete(entity);
} public bool DeleteById(object id)
{
return _postRepository.DeleteById(id);
} public bool DeleteByIds(object[] ids)
{
return _postRepository.DeleteByIds(ids);
} public IEnumerable<Post> FindAll()
{
return _postRepository.FindAll();
} public Post FindById(int id)
{
return _postRepository.FindById(id);
} public int Insert(Post entity)
{
return _postRepository.Insert(entity);
} public bool Update(Post entity)
{
return _postRepository.Update(entity);
}
}
}

最后,我们再切换到仓储层,在PostRepository文件中使用IPostRepository接口并使用SqlSugar实现该接口中的所有数据操作的方法,

PostRepository.cs

using System.Collections.Generic;
using TsBlog.Domain.Entities; namespace TsBlog.Repositories
{
/// <summary>
/// POST表的数据库操作类
/// </summary>
public class PostRepository : IPostRepository
{
/// <summary>
/// 根据ID查询
/// </summary>
/// <param name="id">Post ID</param>
/// <returns></returns>
public Post FindById(int id)
{
using (var db = DbFactory.GetSqlSugarClient())
{
var entity = db.Queryable<Post>().Single(x => x.Id == id);
return entity;
}
} /// <summary>
/// 查询所有数据(无分页,大数量时请慎用)
/// </summary>
/// <returns></returns>
public IEnumerable<Post> FindAll()
{
#region SqlSugar读取方式
using (var db = DbFactory.GetSqlSugarClient())
{
var list = db.Queryable<Post>().ToList();
return list;
}
#endregion
} /// <summary>
/// 写入实体数据
/// </summary>
/// <param name="entity">博文实体类</param>
/// <returns></returns>
public int Insert(Post entity)
{
using (var db = DbFactory.GetSqlSugarClient())
{
var i = db.Insertable(entity).ExecuteReturnBigIdentity();
//返回的i是long类型,这里你可以根据你的业务需要进行处理
return (int)i;
}
} /// <summary>
/// 更新实体数据
/// </summary>
/// <param name="entity">博文实体类</param>
/// <returns></returns>
public bool Update(Post entity)
{
using (var db = DbFactory.GetSqlSugarClient())
{
//这种方式会以主键为条件
var i = db.Updateable(entity).ExecuteCommand();
return i > 0;
}
} /// <summary>
/// 根据实体删除一条数据
/// </summary>
/// <param name="entity">博文实体类</param>
/// <returns></returns>
public bool Delete(Post entity)
{
using (var db = DbFactory.GetSqlSugarClient())
{
var i = db.Deleteable(entity).ExecuteCommand();
return i > 0;
}
} /// <summary>
/// 删除指定ID的数据
/// </summary>
/// <param name="id">主键ID</param>
/// <returns></returns>
public bool DeleteById(object id)
{
using (var db = DbFactory.GetSqlSugarClient())
{
var i = db.Deleteable<Post>(id).ExecuteCommand();
return i > 0;
}
} /// <summary>
/// 删除指定ID集合的数据(批量删除)
/// </summary>
/// <param name="ids">主键ID集合</param>
/// <returns></returns>
public bool DeleteByIds(object[] ids)
{
using (var db = DbFactory.GetSqlSugarClient())
{
var i = db.Deleteable<Post>().In(ids).ExecuteCommand();
return i > 0;
}
}
}
}

到这里,我们的仓储和服务层准备工作就完成了,接下来安装依赖注入组件:Autofac

安装Autofac

选择解决方案夹[2.Persentation]中的Web项目[TsBlog.Frontend],在"引用"("References")上单击右键,调出Nuget程序包管理界面,搜索"autofac",如下:

Autofac的当前版本为:v4.6.2

同时,再搜索"Autofac.Mvc5",如下:

配置/注册依赖选项

Autofac安装完成之后,我们需要对依赖的接口对实现在Autofac中进行注册,本示例的Autofac配置在Global.asax文件中(请确保TsBlog.Frontend项目中引用了:TsBlog.Domain,TsBlog.Repositories,TsBlog.Servcies这本个项目),如下:

Global.asax

using Autofac;
using Autofac.Integration.Mvc;
using System.Web.Mvc;
using System.Web.Routing;
using TsBlog.Repositories;
using TsBlog.Services; namespace TsBlog.Frontend
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//BundleConfig.RegisterBundles(BundleTable.Bundles); AutofacRegister();
} private void AutofacRegister()
{
var builder = new ContainerBuilder(); //注册MvcApplication程序集中所有的控制器
builder.RegisterControllers(typeof(MvcApplication).Assembly); //注册仓储层服务
builder.RegisterType<PostRepository>().As<IPostRepository>();
//注册服务层服务
builder.RegisterType<PostService>().As<IPostService>(); //注册过滤器
builder.RegisterFilterProvider(); var container = builder.Build(); //设置依赖注入解析器
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}

然后,我们修改控制器文件夹中的HomeController,修改后的代码如下:

HomeController.cs

using System.Web.Mvc;
using TsBlog.Services; namespace TsBlog.Frontend.Controllers
{
public class HomeController : Controller
{
private readonly IPostService _postService;
public HomeController(IPostService postService)
{
_postService = postService;
}
public ActionResult Index()
{
return View();
} public ActionResult Post()
{
//var postRepository = new PostRepository();
//var post = postRepository.FindById(1);
//return View(post); var post = _postService.FindById(1);
return View(post);
}
}
}

再次按F5运行,打开页面:http://localhost:54739/home/post,这次我们可以看到和前两篇一样的运行效果了:

本文的源码托管地址:https://github.com/lampo1024/TsBlog/releases/tag/v1.4

本文学习到此结束,本系列未完待续......

如果你喜欢Rector的本系列文章,请为我点个大大的赞,以支持Rector在后续的写作中更有基(激)情,哈哈。。。

本文同步发表至 图享网一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](四)

一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](四)的更多相关文章

  1. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](五)

    前言 Hi,大家好,我是Rector 时间飞逝,一个星期又过去了,今天还是星期五,Rector在图享网继续跟大家分享系列文本:一步一步创建ASP.NET MVC5程序[Repository+Autof ...

  2. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](一)

    前言 大家好,我是Rector 从今天开始,Rector将为大家推出一个关于创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar]的文章系列, ...

  3. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](三)

    前言 上一篇<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)>我们通过如下操作: 创建实体及工具类 创建Re ...

  4. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)

    前言: 在本系列第一篇<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](一)>中,我为大家介绍了搭建空白解决方案以 ...

  5. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](六)

    前言 大家好,我是Rector 又是星期五,很兴奋,很高兴,很high...啦啦啦... Rector在图享网又和大家见面啦!!!上一篇<一步一步创建ASP.NET MVC5程序[Reposit ...

  6. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](七)

    前言 大家好,我依旧是你们的老朋友Rector,很高兴又在周五的时候准时和大家见面. Rector的系列文章[一步一步创建ASP.NET MVC5程序[Repository+Autofac+Autom ...

  7. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](八)

    前言 Hi, 大家好,还是星期五,还是Rector,又在图享网准时和大家见面了. 今天给大家带来系列教程<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Auto ...

  8. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](九)

    前言 童鞋们,大家好 我是专注.NET开发者社区建设的实践者Rector. 首先,为自己间隔了两个星期五再更新本系列文章找个不充分的理由:Rector最近工作,家庭的各种事务所致,希望大家谅解. 本文 ...

  9. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](十)

    前言 朋友们, 大家好,我还是Rector,写ASP.NET MVC 5系列文章[一步一步创建ASP.NET MVC5程序Repository+Autofac+Automapper+SqlSugar] ...

随机推荐

  1. Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/context/embedded/ServletRegistrationBean

    异常信息 2017-09-02 18:06:37.223 [main] ERROR o.s.boot.SpringApplication - Application startup failed ja ...

  2. intellij安装lombok插件,解决注解@Slf4j注入后找不到变量log

    1.进入设置 2.搜索插件 3.安装

  3. 58、js扩展

    作用域是JavaScript最重要的概念之一,想要学好JavaScript就需要理解JavaScript作用域和作用域链的工作原理. 一.js的作用域 任何程序设计语言都有作用域的概念,简单的说,作用 ...

  4. LeetCode #1 TwoSum

    Description Given an array of integers, return indices of the two numbers such that they add up to a ...

  5. Swift3.0 创建工程常用的类、三方、以及扩展 1.5

    搭建项目常用的方法属性,欢迎追加 三方: source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_framew ...

  6. kvm 随笔

    1. 查看kvm虚拟机状态 # virsh list --all   2. KVM虚拟机开机 # virsh start windows   3. KVM虚拟机关机或断电 (1) 关机 virsh关机 ...

  7. ABP .Net Core Entity Framework迁移使用MySql数据库

    一.迁移说明 ABP模板项目Entity Framework Core默认使用的是Sql Server,也很容易将数据库迁移到MySQL,步骤如下. 二.迁移MySQL步骤 1. 下载项目 请到 ht ...

  8. nginx编译参数的内容

    最近公司安排我安装几台云服务器环境 采用nginx做反向代理: 查了一下官方文档,参数比较多,很多在上线后 可能才知道注意一下的. 编译安装nginx的话 需要安装一些前置组件: 1.gcc环境:用于 ...

  9. open-falcon(v0.2)部署手册(源码编译)

    今天安装falcon-plus,下面为用基础环境配置. centos 6.8  alisql5.6.32   redis-3.2.8 cmake-3.9.1 bison-3.0 openssl-1.0 ...

  10. su 和 sudo 命令的区别-转载

    link 一. 使用 su 命令临时切换用户身份                   1.su 的适用条件和威力   su命令就是切换用户的工具,怎么理解呢?比如我们以普通用户beinan登录的,但要 ...