最近接了幾個小單子,由於是小單子,項目規模都比較小,業務相對來講,也比較簡單。因此在選擇架構的時候,考慮到效率方面的因素,就採起了asp.net+entity framework中的code first模式,從而能夠進行快速開發。幾個單子作完下來,順便總結整理一下,近些時候也一直在學習dotnetcore,索性將項目都升級了,因而便有了這一套「基於EF Core的Code First模式的DotNetCore快速開發框架」。至於code first模式的優劣,此文將再也不贅述。至於本文的目的,一是爲了總結和整理工做這幾年所學的一些知識,方便之後可以快速高效地接入項目中。再是分享出來,跟你們一塊兒探討學習,一塊兒進步。歡迎各路大佬指正和建議^_^git
GitHub:github
dotnetcore版本:https://github.com/VictorTzeng/Zxw.Framework.NetCoreredis
.net framework版本:https://github.com/VictorTzeng/Zxw.Framework.Nfx數據庫
碼雲:緩存
dotnetcore版本:https://gitee.com/ceo_bitch/Zxw.Framework.NetCore架構
.net framework版本:https://gitee.com/ceo_bitch/Zxw.Framework.Nfxapp
此項目主要分紅兩部分:Zxw.Framework.NetCore (核心類庫)和 NetCore.Sample (示例)兩部分。如圖所示:框架
Zxw.Framework.NetCore 項目說明:asp.net
如 NetCore.Sample 所示,按照此項目結構建立好:ide
安裝nuget package:
Install-Package Zxw.Framework.NetCore -Version 1.0.1
須要注意如下幾點:
實體示例:
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 }
在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 }
使用代碼生成器:
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 }
寫博客真的很費力,但願本身可以堅持下去。
最後,歡迎各路大佬建議和拍磚~~