前言
最近接了几个小单子,因为是小单子,项目规模都比较小,业务相对来说,也比较简单。所以在选择架构的时候,考虑到效率方面的因素,就采取了asp.net+entity framework中的code first模式,从而可以进行快速开发。几个单子做完下来,顺便总结整理一下,近些时候也一直在学习dotnetcore,索性将项目都升级了,于是便有了这一套“基于EF Core的Code First模式的DotNetCore快速开发框架”。至于code first模式的优劣,此文将不再赘述。至于本文的目的,一是为了总结和整理工作这几年所学的一些知识,方便以后能够快速高效地接入项目中。再是分享出来,跟大家一起探讨学习,一起进步。欢迎各路大佬指正和建议^_^
项目地址
GitHub:
dotnetcore版本:https://github.com/VictorTzeng/Zxw.Framework.NetCore
.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.Nfx
项目架构
此项目主要分成两部分: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这四个项目没有单独建立,调用代码生成器生成的代码将存在于调用项目的目录下
- 利用代码生成器生成的代码文件需要手动添加到项目中
实体示例:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Zxw.Framework.NetCore.Models; namespace Zxw.Framework.Website.Models
{
public class TutorClassType:IBaseModel<int>
{
[Key]
[Column("TutorClassTypeId")]
public int Id { get; set; } [Required]
[StringLength(maximumLength:)]
public string TutorClassTypeName { get; set; }
public bool Active { get; set; } = true;
[StringLength(maximumLength:)]
public string Remark { get; set; }
public int TutorClassCount { get; set; }
}
}
在Startup.cs文件中使用:
using System;
using System.Text;
using log4net;
using log4net.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Zxw.Framework.NetCore.EfDbContext;
using Zxw.Framework.NetCore.Filters;
using Zxw.Framework.NetCore.Helpers;
using Zxw.Framework.NetCore.IoC;
using Zxw.Framework.NetCore.Options; namespace Zxw.Framework.Website
{
public class Startup
{
public static ILoggerRepository repository { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//初始化log4net
repository = LogManager.CreateRepository("NETCoreRepository");
Log4NetHelper.SetConfig(repository, "log4net.config");
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc(option=>
{
option.Filters.Add(new GlobalExceptionFilter());
});
services.AddMemoryCache();//启用MemoryCache
services.AddDistributedRedisCache(option =>
{
option.Configuration = "localhost";//redis连接字符串
option.InstanceName = "";//Redis实例名称
});//启用Redis
services.Configure<MemoryCacheEntryOptions>(
options => options.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes()) //设置MemoryCache缓存有效时间为5分钟。
.Configure<DistributedCacheEntryOptions>(option =>
option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes());//设置Redis缓存有效时间为5分钟。
return InitIoC(services);
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
} app.UseStaticFiles(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
/// <summary>
/// IoC初始化
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
private IServiceProvider InitIoC(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("MsSqlServer");
var dbContextOption = new DbContextOption
{
ConnectionString = connectionString,
ModelAssemblyName = "Zxw.Framework.Website.Models",
DbType = DbType.MSSQLSERVER
};
var codeGenerateOption = new CodeGenerateOption
{
ModelsNamespace = "Zxw.Framework.Website.Models",
IRepositoriesNamespace = "Zxw.Framework.Website.IRepositories",
RepositoriesNamespace = "Zxw.Framework.Website.Repositories",
IServicsNamespace = "Zxw.Framework.Website.IServices",
ServicesNamespace = "Zxw.Framework.Website.Services"
};
IoCContainer.Register(Configuration);//注册配置
IoCContainer.Register(dbContextOption);//注册数据库配置信息
IoCContainer.Register(codeGenerateOption);//注册代码生成器相关配置信息
IoCContainer.Register(typeof(DefaultDbContext));//注册EF上下文
IoCContainer.Register("Zxw.Framework.Website.Repositories", "Zxw.Framework.Website.IRepositories");//注册仓储
IoCContainer.Register("Zxw.Framework.Website.Services", "Zxw.Framework.Website.IServices");//注册service
return IoCContainer.Build(services);
}
}
}
使用代码生成器:
using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Zxw.Framework.NetCore.CodeGenerator;
using Zxw.Framework.NetCore.Helpers;
using Zxw.Framework.Website.IServices;
using Zxw.Framework.Website.ViewModels;
using Zxw.Framework.Website.Models; namespace Zxw.Framework.Website.Controllers
{
public class HomeController : Controller
{
private ITutorClassTypeService iTutorClassTypeService; public HomeController(ITutorClassTypeService tutorClassTypeService)
{
if(tutorClassTypeService==null)
throw new ArgumentNullException(nameof(tutorClassTypeService));
iTutorClassTypeService = tutorClassTypeService;
}
public IActionResult Index()
{
CodeGenerator.Generate();//生成所有实体类对应的Repository和Service层代码文件
CodeGenerator.GenerateSingle<TutorClassType, int>();//生成单个实体类对应的Repository和Service层代码文件 return View();
} public IActionResult About()
{
ViewData["Message"] = "Your application description page."; return View();
} public IActionResult Contact()
{
ViewData["Message"] = "Your contact page."; return View();
} public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
} protected override void Dispose(bool disposing)
{
if (disposing)
{
iTutorClassTypeService.Dispose();
}
base.Dispose(disposing);
}
}
}
总结
写博客真的很费力,希望自己能够坚持下去。
最后,欢迎各路大佬建议和拍砖~~