一步一步創(chuàng)建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](四)

前言

上一篇《一步一步創(chuàng)建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](三)》,我們完成了:
* 引用SqlSugar
* 使用SqlSugar對(duì)Repository類的改造
并成功使用PostRepository來查詢到了數(shù)據(jù),今天我們來創(chuàng)建一個(gè)新的服務(wù)層以及安裝配置依賴注入框架組件Autofac等。

本篇知識(shí)要點(diǎn)

* 創(chuàng)建服務(wù)層:TsBlog.Services
* 創(chuàng)建服務(wù)接口
* 實(shí)現(xiàn)服務(wù)接口
* 創(chuàng)建倉(cāng)儲(chǔ)接口
* 安裝Autofac依賴注入組件
* 注冊(cè)配置Autofac 依賴注入

教程內(nèi)容

創(chuàng)建服務(wù)層

選中解決方案中的解決方案文件夾[1.Libraries],右鍵單擊=>>添加=>>新項(xiàng)目,在彈出的對(duì)話框中添加一個(gè).NET Framework 4.6.2的C#類庫(kù)項(xiàng)目,命名為:TsBlog.Services。項(xiàng)目創(chuàng)建成功后,刪除自動(dòng)生成的Class1.cs文件。

由于服務(wù)層需要依賴于倉(cāng)儲(chǔ)層,所以首先切換到倉(cāng)儲(chǔ)層[TsBlog.Repositories]項(xiàng)目中,創(chuàng)建博文的倉(cāng)儲(chǔ)接口類:IPostRepository,代碼如下:

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

namespace TsBlog.Repositories
{
    public interface IPostRepository
    {
        /// <summary>
        /// 根據(jù)ID查詢單條數(shù)據(jù)
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        Post FindById(int id);
        /// <summary>
        /// 查詢所有數(shù)據(jù)(無分頁(yè),大數(shù)量時(shí)請(qǐng)慎用)
        /// </summary>
        /// <returns></returns>
        IEnumerable<Post> FindAll();

        /// <summary>
        /// 寫入實(shí)體數(shù)據(jù)
        /// </summary>
        /// <param name="entity">博文實(shí)體類</param>
        /// <returns></returns>
        int Insert(Post entity);

        /// <summary>
        /// 更新實(shí)體數(shù)據(jù)
        /// </summary>
        /// <param name="entity">博文實(shí)體類</param>
        /// <returns></returns>
        bool Update(Post entity);

        /// <summary>
        /// 根據(jù)實(shí)體刪除一條數(shù)據(jù)
        /// </summary>
        /// <param name="entity">博文實(shí)體類</param>
        /// <returns></returns>
        bool Delete(Post entity);

        /// <summary>
        /// 刪除指定ID的數(shù)據(jù)
        /// </summary>
        /// <param name="id">主鍵ID</param>
        /// <returns></returns>
        bool DeleteById(object id);

        /// <summary>
        /// 刪除指定ID集合的數(shù)據(jù)(批量刪除)
        /// </summary>
        /// <param name="ids">主鍵ID集合</param>
        /// <returns></returns>
        bool DeleteByIds(object[] ids);
    }
}

再切換到服務(wù)層,在剛才創(chuàng)建的服務(wù)層項(xiàng)目中首先引用倉(cāng)儲(chǔ)層,并分別創(chuàng)建以下服務(wù)接口和類文件:

IPostService.cs:

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

namespace TsBlog.Services
{
    public interface IPostService
    {
        /// <summary>
        /// 根據(jù)ID查詢單條數(shù)據(jù)
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        Post FindById(int id);
        /// <summary>
        /// 查詢所有數(shù)據(jù)(無分頁(yè),大數(shù)量時(shí)請(qǐng)慎用)
        /// </summary>
        /// <returns></returns>
        IEnumerable<Post> FindAll();

        /// <summary>
        /// 寫入實(shí)體數(shù)據(jù)
        /// </summary>
        /// <param name="entity">博文實(shí)體類</param>
        /// <returns></returns>
        int Insert(Post entity);

        /// <summary>
        /// 更新實(shí)體數(shù)據(jù)
        /// </summary>
        /// <param name="entity">博文實(shí)體類</param>
        /// <returns></returns>
        bool Update(Post entity);

        /// <summary>
        /// 根據(jù)實(shí)體刪除一條數(shù)據(jù)
        /// </summary>
        /// <param name="entity">博文實(shí)體類</param>
        /// <returns></returns>
        bool Delete(Post entity);

        /// <summary>
        /// 刪除指定ID的數(shù)據(jù)
        /// </summary>
        /// <param name="id">主鍵ID</param>
        /// <returns></returns>
        bool DeleteById(object id);

        /// <summary>
        /// 刪除指定ID集合的數(shù)據(jù)(批量刪除)
        /// </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);
        }
    }
}

最后,我們?cè)偾袚Q到倉(cāng)儲(chǔ)層,在PostRepository文件中使用IPostRepository接口并使用SqlSugar實(shí)現(xiàn)該接口中的所有數(shù)據(jù)操作的方法,
PostRepository.cs

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

namespace TsBlog.Repositories
{
    /// <summary>
    /// POST表的數(shù)據(jù)庫(kù)操作類
    /// </summary>
    public class PostRepository : IPostRepository
    {
        /// <summary>
        /// 根據(jù)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>
        /// 查詢所有數(shù)據(jù)(無分頁(yè),大數(shù)量時(shí)請(qǐng)慎用)
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Post> FindAll()
        {
            #region SqlSugar讀取方式
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var list = db.Queryable<Post>().ToList();
                return list;
            }
            #endregion
        }


        /// <summary>
        /// 寫入實(shí)體數(shù)據(jù)
        /// </summary>
        /// <param name="entity">博文實(shí)體類</param>
        /// <returns></returns>
        public int Insert(Post entity)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var i = db.Insertable(entity).ExecuteReturnBigIdentity();
                //返回的i是long類型,這里你可以根據(jù)你的業(yè)務(wù)需要進(jìn)行處理
                return (int)i;
            }
        }

        /// <summary>
        /// 更新實(shí)體數(shù)據(jù)
        /// </summary>
        /// <param name="entity">博文實(shí)體類</param>
        /// <returns></returns>
        public bool Update(Post entity)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                //這種方式會(huì)以主鍵為條件
                var i = db.Updateable(entity).ExecuteCommand();
                return i > 0;
            }
        }

        /// <summary>
        /// 根據(jù)實(shí)體刪除一條數(shù)據(jù)
        /// </summary>
        /// <param name="entity">博文實(shí)體類</param>
        /// <returns></returns>
        public bool Delete(Post entity)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var i = db.Deleteable(entity).ExecuteCommand();
                return i > 0;
            }
        }

        /// <summary>
        /// 刪除指定ID的數(shù)據(jù)
        /// </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集合的數(shù)據(jù)(批量刪除)
        /// </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;
            }
        }
    }
}

到這里,我們的倉(cāng)儲(chǔ)和服務(wù)層準(zhǔn)備工作就完成了,接下來安裝依賴注入組件:Autofac

安裝Autofac

選擇解決方案夾[2.Persentation]中的Web項(xiàng)目[TsBlog.Frontend],在"引用"("References")上單擊右鍵,調(diào)出Nuget程序包管理界面,搜索"autofac",如下:

Nuget程序包管理--安裝Autofac
Nuget程序包管理--安裝Autofac

Autofac的當(dāng)前版本為:v4.6.2

同時(shí),再搜索"Autofac.Mvc5",如下:

Nuget程序包管理--安裝Autofac.Mvc5
Nuget程序包管理--安裝Autofac.Mvc5

配置/注冊(cè)依賴選項(xiàng)

Autofac安裝完成之后,我們需要對(duì)依賴的接口對(duì)實(shí)現(xiàn)在Autofac中進(jìn)行注冊(cè),本示例的Autofac配置在Global.asax文件中(請(qǐng)確保TsBlog.Frontend項(xiàng)目中引用了:TsBlog.Domain,TsBlog.Repositories,TsBlog.Servcies這本個(gè)項(xiàng)目),如下:

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();

            //注冊(cè)MvcApplication程序集中所有的控制器
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            //注冊(cè)倉(cāng)儲(chǔ)層服務(wù)
            builder.RegisterType<PostRepository>().As<IPostRepository>();
            //注冊(cè)服務(wù)層服務(wù)
            builder.RegisterType<PostService>().As<IPostService>();

            //注冊(cè)過濾器
            builder.RegisterFilterProvider();

            var container = builder.Build();

            //設(shè)置依賴注入解析器
            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運(yùn)行,打開頁(yè)面:http://localhost:54739/home/post,這次我們可以看到和前兩篇一樣的運(yùn)行效果了:

Autofac運(yùn)行結(jié)果
Autofac運(yùn)行結(jié)果

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

本文學(xué)習(xí)到此結(jié)束,本系列未完待續(xù)......

如果你喜歡Rector的本系列文章,請(qǐng)為我點(diǎn)個(gè)大大的贊,以支持Rector在后續(xù)的寫作中更有基(激)情,哈哈。。。

本文同步發(fā)表至 圖享網(wǎng)一步一步創(chuàng)建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](四)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容