资讯专栏INFORMATION COLUMN

一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper

yy13818512006 / 722人阅读

摘要:前言上一篇一步一步创建程序三,我们完成了引用使用对类的改造并成功使用来查询到了数据,今天我们来创建一个新的服务层以及安装配置依赖注入框架组件等。项目创建成功后,删除自动生成的文件。本文同步发表至码友网一步一步创建程序四

前言

上一篇《一步一步创建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
    {
        /// 
        /// 根据ID查询单条数据
        /// 
        /// ID
        /// 
        Post FindById(int id);
        /// 
        /// 查询所有数据(无分页,大数量时请慎用)
        /// 
        /// 
        IEnumerable FindAll();

        /// 
        /// 写入实体数据
        /// 
        /// 博文实体类
        /// 
        int Insert(Post entity);

        /// 
        /// 更新实体数据
        /// 
        /// 博文实体类
        /// 
        bool Update(Post entity);

        /// 
        /// 根据实体删除一条数据
        /// 
        /// 博文实体类
        /// 
        bool Delete(Post entity);

        /// 
        /// 删除指定ID的数据
        /// 
        /// 主键ID
        /// 
        bool DeleteById(object id);

        /// 
        /// 删除指定ID集合的数据(批量删除)
        /// 
        /// 主键ID集合
        /// 
        bool DeleteByIds(object[] ids);
    }
}

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

IPostService.cs:

using System.Collections.Generic;
using TsBlog.Domain.Entities;

namespace TsBlog.Services
{
    public interface IPostService
    {
        /// 
        /// 根据ID查询单条数据
        /// 
        /// ID
        /// 
        Post FindById(int id);
        /// 
        /// 查询所有数据(无分页,大数量时请慎用)
        /// 
        /// 
        IEnumerable FindAll();

        /// 
        /// 写入实体数据
        /// 
        /// 博文实体类
        /// 
        int Insert(Post entity);

        /// 
        /// 更新实体数据
        /// 
        /// 博文实体类
        /// 
        bool Update(Post entity);

        /// 
        /// 根据实体删除一条数据
        /// 
        /// 博文实体类
        /// 
        bool Delete(Post entity);

        /// 
        /// 删除指定ID的数据
        /// 
        /// 主键ID
        /// 
        bool DeleteById(object id);

        /// 
        /// 删除指定ID集合的数据(批量删除)
        /// 
        /// 主键ID集合
        /// 
        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 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
{
    /// 
    /// POST表的数据库操作类
    /// 
    public class PostRepository : IPostRepository
    {
        /// 
        /// 根据ID查询
        /// 
        /// Post ID
        /// 
        public Post FindById(int id)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var entity = db.Queryable().Single(x => x.Id == id);
                return entity;
            }
        }

        /// 
        /// 查询所有数据(无分页,大数量时请慎用)
        /// 
        /// 
        public IEnumerable FindAll()
        {
            #region SqlSugar读取方式
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var list = db.Queryable().ToList();
                return list;
            }
            #endregion
        }


        /// 
        /// 写入实体数据
        /// 
        /// 博文实体类
        /// 
        public int Insert(Post entity)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var i = db.Insertable(entity).ExecuteReturnBigIdentity();
                //返回的i是long类型,这里你可以根据你的业务需要进行处理
                return (int)i;
            }
        }

        /// 
        /// 更新实体数据
        /// 
        /// 博文实体类
        /// 
        public bool Update(Post entity)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                //这种方式会以主键为条件
                var i = db.Updateable(entity).ExecuteCommand();
                return i > 0;
            }
        }

        /// 
        /// 根据实体删除一条数据
        /// 
        /// 博文实体类
        /// 
        public bool Delete(Post entity)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var i = db.Deleteable(entity).ExecuteCommand();
                return i > 0;
            }
        }

        /// 
        /// 删除指定ID的数据
        /// 
        /// 主键ID
        /// 
        public bool DeleteById(object id)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var i = db.Deleteable(id).ExecuteCommand();
                return i > 0;
            }
        }

        /// 
        /// 删除指定ID集合的数据(批量删除)
        /// 
        /// 主键ID集合
        /// 
        public bool DeleteByIds(object[] ids)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var i = db.Deleteable().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().As();
            //注册服务层服务
            builder.RegisterType().As();

            //注册过滤器
            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/...

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

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

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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/110502.html

相关文章

  • 步一创建ASP.NET MVC5程序[Repository+Autofac+Automapper

    摘要:开发人员需要作的事则是通过配置两个实体对象之间的一些映射关系。提供了一些简单配置,还有一些简单的映射测试。所以,再在解决方案目录下创建一个名为的项目,这个项目只存放关于视图实体的类文件。本文同步发表至码友网一步一步创建程序五 前言 Hi,大家好,我是Rector 时间飞逝,一个星期又过去了,今天还是星期五,Rector在码友网继续跟大家分享系列文本:一步一步创建ASP.NET MVC5...

    chengjianhua 评论0 收藏0
  • 步一创建ASP.NET MVC5程序[Repository+Autofac+Automapper

    摘要:我们新建页面时只需要基于这个母版页,就会自动继承母版页面的通用布局部分,比如头部导航菜单栏页面底部信息等等。那么现在就把本示例中的头部导航页脚区域作为共用区域提取出来,放到母版页中。但是请注意,一个母版页中只能有一个标记。 前言 朋友们,大家好,我还是Rector,写ASP.NET MVC 5系列文章 [一步一步创建ASP.NET MVC5程序Repository+Autofac+Au...

    王岩威 评论0 收藏0
  • 步一创建ASP.NET MVC5程序[Repository+Autofac+Automapper

    摘要:前言大家好,我依旧是你们的老朋友,很高兴又在周五的时候准时和大家见面。如果遇到问题,欢迎加入码友网官方群本文来源码友网一步一步创建程序七 前言 大家好,我依旧是你们的老朋友Rector,很高兴又在周五的时候准时和大家见面。 Rector的系列文章【一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar]】从写作以来,已经出...

    ky0ncheng 评论0 收藏0
  • 步一创建ASP.NET MVC5程序[Repository+Autofac+Automapper

    摘要:今天我们就引入一个国内开发者开发并维护的开源框架。本文同步发表至码友网一步一步创建程序三 前言 上一篇《一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)》我们通过如下操作: 创建实体及工具类 创建Repository类 完善View层 修改控制器 创建视图 数据库连接 创建数据库和表 实现了简单的...

    vpants 评论0 收藏0
  • 步一创建ASP.NET MVC5程序[Repository+Autofac+Automapper

    摘要:在码友网又和大家见面啦上一篇一步一步创建程序五我们完成了是什么简述安装的配置的应用通过前面几篇文章的学习,本系列一步一步创建程序中主要涉及到的技术和组件已基本介绍到位了。本文来源码友网一步一步创建程序六 前言 大家好,我是Rector 又是星期五,很兴奋,很高兴,很high...啦啦啦。。。Rector在码友网又和大家见面啦!!!上一篇《一步一步创建ASP.NET MVC5程序[Rep...

    Sanchi 评论0 收藏0

发表评论

0条评论

阅读需要支付1元查看
<