net core天馬行空系列:下降net core門檻,數據庫操做和http訪問僅需寫接口,實現類由框架動態生成

引文

  hi,你們好,我是三合。不知各位有沒有想過,若是能把數據庫操做和http訪問都統一封裝成接口(interface)的形式,
而後接口對應的實現類由框架去自動生成,那麼必然能大大下降工做量,由於不須要去寫不少重複的代碼了,還有一個好處是,都是提供接口,咱們把原來數據庫操做的部分,改爲http訪問,對於業務層來講,是無感的,由於接口和方法都沒變。致力於下降上手net core的門檻,我開源了SummerBoot項目,下面讓咱們來看一下效果。java

數據庫表對應實體類,這些都是常規操做,略過

重頭戲,如何寫接口,以一個簡單的購物功能爲例子

數據庫訪問

訂單詳情倉儲

訂單倉儲

http訪問

控制器中進行構造函數注入

實際調用

/// <summary>
        /// 添加訂單
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("AddOrder")]
        public async Task<IActionResult> AddOrder([FromBody]AddOrderDto dto)
        {
            if (dto?.ProductList==null) return BadRequest("參數不能爲空");

            Uow.BeginTransaction();
            try
            {
                var orderHeader = new OrderHeader
                {
                    CreateTime = DateTime.UtcNow,
                    CustomerNo = dto.CustomerNo,
                    State = 1,
                    OrderNo = Guid.NewGuid().ToString("N")
                };

                await OrderHeaderRepository.InsertAsync(orderHeader);

                var orderDetailList = new List<OrderDetail>();
                //總消費金額
                var totalAmount = 0m;
                dto.ProductList.ForEach(it =>
                {
                    var orderDetail = new OrderDetail
                    {
                        OrderHeaderId = orderHeader.Id,
                        ProductNo = it.ProductNo,
                        ProductName = it.ProductName,
                        Quantity = it.Quantity,
                        Price = it.Price
                    };
                    orderDetailList.Add(orderDetail);

                    totalAmount += it.Quantity * it.Price;
                });

                await OrderDetailRepository.BatchInsertAsync(orderDetailList);
                //更新用戶消費金額
                var success = await CustomerRepository.UpdateCustomerAmount(dto.CustomerNo, totalAmount);
                
                if (!success)
                {
                    Uow.RollBack();

                    return BadRequest();
                }
            }
            catch (Exception e)
            {
                Uow.RollBack();
            }
           
            Uow.Commit();

            return Ok();
        }
		
		/// <summary>
		/// 刪庫跑路
		/// </summary>
		/// <returns></returns>
		[HttpGet("DeleteDatabase")]
		public async Task DeleteDatabase()
		{
			await OrderHeaderRepository.DeleteAllOrder();
		}

		/// <summary>
		/// 根據會員編號取消訂單
		/// </summary>
		/// <param name="customerNo"></param>
		/// <returns></returns>
		[HttpGet("CancelOrderByCustomerNo")]
		public async Task<bool> CancelOrderByCustomerNo(string customerNo)
		{
			var count = await OrderHeaderRepository.CancelOrderByCustomerNoAsync(customerNo);
			return count > 0;
		}

		/// <summary>
		/// 分頁,根據會員編號獲取消費詳情
		/// </summary>
		/// <param name="customerNo"></param>
		/// <returns></returns>
		[HttpGet("QueryOrderDetailByCustomerNoByPage")]
		public async Task<Page<OrderDetail>> QueryOrderDetailByCustomerNoByPage(int pageNumber,int pageSize, string customerNo)
		{
			var page=new Pageable(pageNumber,pageSize);
			var result = await OrderDetailRepository.GetOrderDetailByCustomerNoByPageAsync(page,customerNo);
			return result;
		}

		/// <summary>
		/// 根據會員編號獲取消費詳情
		/// </summary>
		/// <param name="customerNo"></param>
		/// <returns></returns>
		[HttpGet("QueryOrderDetailByCustomerNo")]
		public async Task<List<OrderDetail>> QueryOrderDetailByCustomerNo(string customerNo)
		{
			var result= await OrderDetailRepository.GetOrderDetailByCustomerNoAsync(customerNo);
			return result;
		}

動態生成接口實現類的原理

  最開始寫的時候,思路是,採用AOP思想,castle動態生成接口實現類,實現類裏的方法都沒有具體實現,而後在切面裏對方法進行攔截而且模擬方法的實現,提供返回值,java中不少騷操做就是這麼實現的,可是後來發如今.net
中這種實現方式有很大的弊端,由於.net有異步方法,而castle對於異步方法的支持是很弱的,不足以實現最開始的設想,因而,我換了一種思路,在數據庫操做和http調用中,拋開動態實現類這個殼子,具體執行操做的類是恆定不變的,
那麼利用emit技術動態路由到要執行的方法就好了。git

寫在最後

  若是這篇文章對你有所啓發不妨點個贊吧。github

  github地址:https://github.com/TripleView/SummerBoot,歡迎star!數據庫

  QQ羣:799648362框架

  nuget包:SummerBoot異步

相關文章
相關標籤/搜索