前言 最近接了幾個小單子,因為是小單子,項目規模都比較小,業務相對來說,也比較簡單。所以在選擇架構的時候,考慮到效率方面的因素,就採取了asp.net+entity framework中的code first模式,從而可以進行快速開發。幾個單子做完下來,順便總結整理一下,近些時候也一直在學習dotn ...
前言
最近接了幾個小單子,因為是小單子,項目規模都比較小,業務相對來說,也比較簡單。所以在選擇架構的時候,考慮到效率方面的因素,就採取了asp.net+entity framework中的code first模式,從而可以進行快速開發。幾個單子做完下來,順便總結整理一下,近些時候也一直在學習dotnetcore,索性將項目都升級了,於是便有了這一套“基於EF Core的Code First模式的DotNetCore快速開發框架”。至於code first模式的優劣,此文將不再贅述。至於本文的目的,一是為了總結和整理工作這幾年所學的一些知識,方便以後能夠快速高效地接入項目中。再是分享出來,跟大家一起探討學習,一起進步。歡迎各路大佬指正和建議^_^
項目地址:Zxw.Framework
項目架構
此項目主要分成兩部分:Zxw.Framework.NetCore (核心類庫)和 NetCore.Sample (示例)兩部分。如圖所示:
Zxw.Framework.NetCore 項目說明:
- Attributes —— 一些常用的屬性
- CodeGenerator —— 代碼生成器,用於生成Repository和Service層的代碼
- CodeTemplate —— Repository和Service層代碼模板
- EfDbContext —— EF上下文
- Extensions —— 一些常用的擴展方法
- Filters —— 一些常用的攔截器
- Helpers —— 一些常用的幫助類
- IoC —— IoC容器封裝類,Autofac
- IRepositories —— Repository介面類
- IServices —— Service介面類
- Middlewares —— 中間件
- Models —— 實體介面類,IBaseModel<TKey>
- Options —— 一些常用的配置類
- Repositories —— Repository層的父類
- Services —— Service層的父類
框架使用
如 NetCore.Sample 所示,按照此項目結構創建好:
- Zxw.Framework.Website —— 網站
- Zxw.Framework.Website.Controllers —— 控制器
- Zxw.Framework.Website.IRepositories —— 倉儲介面
- Zxw.Framework.Website.IServices —— Service介面
- Zxw.Framework.Website.Models —— 實體
- Zxw.Framework.Website.Repositories —— 倉儲
- Zxw.Framework.Website.Services —— Services
- Zxw.Framework.Website.ViewModels —— ViewModels
安裝nuget package:
Install-Package Zxw.Framework.NetCore -Version 1.0.1
需要註意以下幾點:
- 所有實體都需實現IBaseModel<TKey>介面(TKey是主鍵類型),如果需要在資料庫中生成對應的數據表
- 如果IRepositories、IServices、Repositories、Services這四個項目沒有單獨建立,調用代碼生成器生成的代碼將存在於調用項目的目錄下
- 利用代碼生成器生成的代碼文件需要手動添加到項目中
實體示例:
1 using System.ComponentModel.DataAnnotations; 2 using System.ComponentModel.DataAnnotations.Schema; 3 using Zxw.Framework.NetCore.Models; 4 5 namespace Zxw.Framework.Website.Models 6 { 7 public class TutorClassType:IBaseModel<int> 8 { 9 [Key] 10 [Column("TutorClassTypeId")] 11 public int Id { get; set; } 12 13 [Required] 14 [StringLength(maximumLength:50)] 15 public string TutorClassTypeName { get; set; } 16 public bool Active { get; set; } = true; 17 [StringLength(maximumLength:200)] 18 public string Remark { get; set; } 19 public int TutorClassCount { get; set; } 20 } 21 }View Code
在Startup.cs文件中使用:
1 using System; 2 using System.Text; 3 using log4net; 4 using log4net.Repository; 5 using Microsoft.AspNetCore.Builder; 6 using Microsoft.AspNetCore.Hosting; 7 using Microsoft.Extensions.Caching.Distributed; 8 using Microsoft.Extensions.Caching.Memory; 9 using Microsoft.Extensions.Configuration; 10 using Microsoft.Extensions.DependencyInjection; 11 using Zxw.Framework.NetCore.EfDbContext; 12 using Zxw.Framework.NetCore.Filters; 13 using Zxw.Framework.NetCore.Helpers; 14 using Zxw.Framework.NetCore.IoC; 15 using Zxw.Framework.NetCore.Options; 16 17 namespace Zxw.Framework.Website 18 { 19 public class Startup 20 { 21 public static ILoggerRepository repository { get; set; } 22 public Startup(IConfiguration configuration) 23 { 24 Configuration = configuration; 25 //初始化log4net 26 repository = LogManager.CreateRepository("NETCoreRepository"); 27 Log4NetHelper.SetConfig(repository, "log4net.config"); 28 } 29 30 public IConfiguration Configuration { get; } 31 32 // This method gets called by the runtime. Use this method to add services to the container. 33 public IServiceProvider ConfigureServices(IServiceCollection services) 34 { 35 services.AddMvc(option=> 36 { 37 option.Filters.Add(new GlobalExceptionFilter()); 38 }); 39 services.AddMemoryCache();//啟用MemoryCache 40 services.AddDistributedRedisCache(option => 41 { 42 option.Configuration = "localhost";//redis連接字元串 43 option.InstanceName = "";//Redis實例名稱 44 });//啟用Redis 45 services.Configure<MemoryCacheEntryOptions>( 46 options => options.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)) //設置MemoryCache緩存有效時間為5分鐘。 47 .Configure<DistributedCacheEntryOptions>(option => 48 option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5));//設置Redis緩存有效時間為5分鐘。 49 return InitIoC(services); 50 } 51 52 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 53 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 54 { 55 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); 56 if (env.IsDevelopment()) 57 { 58 app.UseDeveloperExceptionPage(); 59 app.UseBrowserLink(); 60 } 61 else 62 { 63 app.UseExceptionHandler("/Home/Error"); 64 } 65 66 app.UseStaticFiles(); 67 68 app.UseMvc(routes => 69 { 70 routes.MapRoute( 71 name: "default", 72 template: "{controller=Home}/{action=Index}/{id?}"); 73 }); 74 } 75 /// <summary> 76 /// IoC初始化 77 /// </summary> 78 /// <param name="services"></param> 79 /// <returns></returns> 80 private IServiceProvider InitIoC(IServiceCollection services) 81 { 82 var connectionString = Configuration.GetConnectionString("MsSqlServer"); 83 var dbContextOption = new DbContextOption 84 { 85 ConnectionString = connectionString, 86 ModelAssemblyName = "Zxw.Framework.Website.Models", 87 DbType = DbType.MSSQLSERVER 88 }; 89 var codeGenerateOption = new CodeGenerateOption 90 { 91 ModelsNamespace = "Zxw.Framework.Website.Models", 92 IRepositoriesNamespace = "Zxw.Framework.Website.IRepositories", 93 RepositoriesNamespace = "Zxw.Framework.Website.Repositories", 94 IServicsNamespace = "Zxw.Framework.Website.IServices", 95 ServicesNamespace = "Zxw.Framework.Website.Services" 96 }; 97 IoCContainer.Register(Configuration);//註冊配置 98 IoCContainer.Register(dbContextOption);//註冊資料庫配置信息 99 IoCContainer.Register(codeGenerateOption);//註冊代碼生成器相關配置信息 100 IoCContainer.Register(typeof(DefaultDbContext));//註冊EF上下文 101 IoCContainer.Register("Zxw.Framework.Website.Repositories", "Zxw.Framework.Website.IRepositories");//註冊倉儲 102 IoCContainer.Register("Zxw.Framework.Website.Services", "Zxw.Framework.Website.IServices");//註冊service 103 return IoCContainer.Build(services); 104 } 105 } 106 }View Code
使用代碼生成器:
1 using System; 2 using System.Diagnostics; 3 using Microsoft.AspNetCore.Mvc; 4 using Zxw.Framework.NetCore.CodeGenerator; 5 using Zxw.Framework.NetCore.Helpers; 6 using Zxw.Framework.Website.IServices; 7 using Zxw.Framework.Website.ViewModels; 8 using Zxw.Framework.Website.Models; 9 10 namespace Zxw.Framework.Website.Controllers 11 { 12 public class HomeController : Controller 13 { 14 private ITutorClassTypeService iTutorClassTypeService; 15 16 public HomeController(ITutorClassTypeService tutorClassTypeService) 17 { 18 if(tutorClassTypeService==null) 19 throw new ArgumentNullException(nameof(tutorClassTypeService)); 20 iTutorClassTypeService = tutorClassTypeService; 21 } 22 public IActionResult Index() 23 { 24 CodeGenerator.Generate();//生成所有實體類對應的Repository和Service層代碼文件 25 CodeGenerator.GenerateSingle<TutorClassType, int>();//生成單個實體類對應的Repository和Service層代碼文件 26 27 return View(); 28 } 29 30 public IActionResult About() 31 { 32 ViewData["Message"] = "Your application description page."; 33 34 return View(); 35 } 36 37 public IActionResult Contact() 38 { 39 ViewData["Message"] = "Your contact page."; 40 41 return View(); 42 } 43 44 public IActionResult Error() 45 { 46 return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); 47 } 48 49 protected override void Dispose(bool disposing) 50 { 51 if (disposing) 52 { 53 iTutorClassTypeService.Dispose(); 54 } 55 base.Dispose(disposing); 56 } 57 } 58 }View Code
總結
寫博客真的很費力,希望自己能夠堅持下去。