1. 程式人生 > 其它 >9、設計模式之外觀模式

9、設計模式之外觀模式

netcore3.1API+efcore快速搭建

框架結構#

實體層 Aer.Enties#

Models-->實體類

業務層 After.IService#

IAltestitemController.cs

業務層 After.Service#

AlltestitemService.cs

介面層 AfterCore#

Controllers-> AlltestitemController.cs

一 EF從資料庫生成實體類到Enties#

1.執行以下語句安裝依賴包#

Copy
Install-Package MySql.Data.EntityFrameworkCore -Pre
Install-Package Pomelo.EntityFrameworkCore.MySql
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

2.在程式包包管理器控制檯#

Copy
Scaffold-DbContext "server=localhost;userid=root;pwd=1;port=3306;database=syerp;sslmode=none;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -Force

二 業務層#

新增IAlltestitemService.cs介面

Copy
using AfterCore.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace After.IService
{
   public interface IAlltestitemService
    {
        /// <summary>
        /// 查詢所有
        /// </summary>
        /// <returns></returns>
        Task<List<Alltestitem>> GetAllAsync();

        /// <summary>
        /// 查詢總數
        /// </summary>
        /// <returns></returns>
        Task<int> CountAsync();
    }
}

After.Service介面實現

AlltestitemService.cs

Copy
using After.IService;
using AfterCore.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace After.Service
{
    public class AlltestitemService : IAlltestitemService
    {
        private readonly testContext _testDbContext;//DB
        public AlltestitemService(testContext testContexts)
        {
            _testDbContext = testContexts;
        }

        public async Task<int> CountAsync()
        {
            return await _testDbContext.Alltestitem.CountAsync();
        }

        public async Task<List<Alltestitem>> GetAllAsync()
        {
            return await _testDbContext.Alltestitem.ToListAsync();

        }
    }
}

三 註冊DbContext#

appsettings.json#

Copy
"ConnectionStrings": {
    "DefaultConnection": "Server=;database=test;uid=root;pwd=m;"
  },

Startup.cs#

Copy
  //註冊DbContext  ConfigureServices
            services.AddDbContext<testContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
 services.AddScoped<IAlltestitemService, AlltestitemService>();//ioc

四 新增Swagger#

安裝依賴包#

Copy
Swashbuckle.AspNetCore

ConfigureServices(IServiceCollection services)#

Copy
//註冊swagger服務
            services.AddSwaggerGen(c =>
              {
                  c.SwaggerDoc("v1", new OpenApiInfo
                  {
                      Version = "v1",
                      Title = "SN部落格 API",
                      Description = "EFCore資料操作 ASP.NET Core Web API",
                      TermsOfService = new Uri("https://example.com/terms"),
                      Contact = new OpenApiContact
                      {
                          Name = "Shayne Boyer",
                          Email = string.Empty,
                          Url = new Uri("https://twitter.com/spboyer"),
                      },
                      License = new OpenApiLicense
                      {
                          Name = "Use under LICX",
                          Url = new Uri("https://example.com/license"),
                      }
                  });

                  // 為 Swagger 設定xml文件註釋路徑
                  var basePath2 = AppContext.BaseDirectory;// xml路徑
                  //var xmlModelPath = Path.Combine(basePath2, "Snblog.Enties.xml");//Model層的xml檔名
                  var corePath = Path.Combine(basePath2, "AfterCore.xml");//API層的xml檔名
                  //c.IncludeXmlComments(xmlModelPath);
                  c.IncludeXmlComments(corePath, true);
                  //新增對控制器的標籤(描述)
                  c.CustomSchemaIds(type => type.FullName);// 可以解決相同類名會報錯的問題

                  // c.OperationFilter<AddResponseHeadersFilter>();
                  // c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
                  //
                  // c.OperationFilter<SecurityRequirementsOperationFilter>();

              });

Configure(IApplicationBuilder app, IWebHostEnvironment env)#

Copy
 #region Swagger
            //可以將Swagger的UI頁面配置在Configure的開發環境之中
            app.UseSwagger();
            //和Swagger UI
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "SN部落格API");
                c.RoutePrefix = string.Empty;
            });
            #endregion

五 顯示層AfterCore#

Controllers->AlltestitemController.cs

Copy
using After.IService;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
//預設的約定集將應用於程式集中的所有操作:
[assembly: ApiConventionType(typeof(DefaultApiConventions))]
namespace AfterCore.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AlltestitemController : ControllerBase
    {
          private readonly IAlltestitemService _service; //IOC依賴注入

         public AlltestitemController(IAlltestitemService service)
        {
            _service = service;
        
        }
        /// <summary>
        /// 查詢所有
        /// </summary>
        /// <returns></returns>
        // [ApiExplorerSettings(IgnoreApi = true)] //隱藏介面 或者直接對這個方法 private,也可以直接使用obsolete屬性
        [HttpGet("GetAllAsync")]
        public async Task<IActionResult> GetAllAsync()
        {
            return Ok(await _service.GetAllAsync());
        }

         /// <summary>
        /// 查詢總數
        /// </summary>
        /// <returns></returns>
        // [ApiExplorerSettings(IgnoreApi = true)] //隱藏介面 或者直接對這個方法 private,也可以直接使用obsolete屬性
        [HttpGet("CountAsync")]
        public async Task<IActionResult> CountAsync()
        {
            return Ok(await _service.CountAsync());
        }
    }
}

執行#