全球观点:面向接口编程实践之aspnetcoreapi的抽象

时间:2023-04-18 21:39:37 来源: 博客园

最为一名越过菜鸟之后的开发,需要做接口开发。下面做一个纯粹的接口编程的实例demo,仅仅是一个webapi接口的抽象。


(资料图片)

下面是代码接口,AbsEFWork是webapi,BaseEntityFramework是一个接口库。

先介绍一下webapi的实现,代码是从底层往上层写的,阅读代码的习惯应该是自上向下。

public class ProductController : CustomController    {        public ProductController(IEFCoreService efCoreService) : base(efCoreService)        {        }    }

控制器代码很简单的实现了CustomController,数据载体是Product。

using BaseEntityFramework.Implementations;using BaseEntityFramework.Implementations.Entitys;using BaseEntityFramework.IService;using Microsoft.EntityFrameworkCore;namespace BaseEntityFramework{    public class Program    {        public static void Main(string[] args)        {            var builder = WebApplication.CreateBuilder(args);            // Add services to the container.            builder.Services.AddControllers();            builder.Services.AddDbContext(options => options.UseInMemoryDatabase("memorydb"));            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle            builder.Services.AddEndpointsApiExplorer();            builder.Services.AddSwaggerGen();            builder.Services.AddScoped, EFCoreProductService>();            var app = builder.Build();            // Configure the HTTP request pipeline.            if (app.Environment.IsDevelopment())            {                app.UseSwagger();                app.UseSwaggerUI();            }            app.UseHttpsRedirection();            app.UseAuthorization();            app.MapControllers();            app.Run();        }    }}

Program启动程序需要实现IEFCoreService的注入,以及ProductDbContext 的内存实现。

这样就可以启动一个swagger

对于product数据存储的具体实现,实体类product和dbcontext必须要自己去实现它。

public class Product:IEntity    {        [Key]        public int Id { get; set; }        public string Name { get; set; }        public string Description { get; set; }        [Column(TypeName = "decimal(28,16)")]        public decimal Price { get; set; }    }
using BaseEntityFramework.Implementations.Entitys;using Microsoft.EntityFrameworkCore;namespace BaseEntityFramework.Implementations{    public class ProductDbContext:DbContext    {        public ProductDbContext(DbContextOptions dbContextOptions):base(dbContextOptions)        {        }         public DbSet Products { get; set; }    }}

查看上面的控制器代码,有注入IEFCoreService的业务代码,对于接口肯定是需要一个实现,这里可以再次封装一个抽象的基类来(温馨提示:重复的代码,必须优化),我这里暂时没做处理。

using BaseEntityFramework.Implementations.Entitys;using BaseEntityFramework.IService;using BaseEntityFramework.Models;using Microsoft.EntityFrameworkCore;using System.Linq.Expressions;namespace BaseEntityFramework.Implementations{    public class EFCoreProductService : IEFCoreService    {        private readonly ProductDbContext _dbContext;        public EFCoreProductService(ProductDbContext productDbContext)        {            _dbContext = productDbContext;        }        public async Task Add(Product entity)        {            _dbContext.Products.Add(entity);            var result = await _dbContext.SaveChangesAsync();            return result != 0;        }        public Task Delete(Product entity)        {            throw new NotImplementedException();        }        public async Task> GetAll()        {            var result =await _dbContext.Products.ToListAsync();            return result;        }        public Task GetEntity(Expression> expression)        {            throw new NotImplementedException();        }        public async Task> GetList(Expression> expression)        {            var result = await _dbContext.Products.Where(expression).ToListAsync();            return result.AsReadOnly();        }        public Task> GetPageResult(PageInput pagInput) where Req : new()        {            throw new NotImplementedException();        }        public Task Update(Product entity)        {            throw new NotImplementedException();        }    }}

上面的代码很简单易懂,最大的好处就是可以复用。实体类和 dbcontext越多这个简简单单的结构就越是有用。

BaseEntityFramework的核心逻辑就是把业务代码做了抽象,做了一个统一的模板,不管 是从那方便说都只有好处。而且作为开发只关心自己的业务代码这一块。

public interface IEFCoreService where T:IEntity    {        Task Add(T entity) ;        Task Delete(T entity);        Task Update(T entity);        Task> GetList(Expression> expression) ;        Task> GetPageResult(PageInput pagInput) where Req:new();        Task GetEntity(Expression> expression);        Task> GetAll();    }

以上的实例只是一个简单的demo,项目中需要做框架的话这或许是一个开始,需要做的远远不止这些。

源代码:

liuzhixin405/AbsEFWork (github.com)

标签:

精彩推送

中国互联网2022年报盘点 全球快看点

中国互联网策源地——中关村一隅。时代的浪潮正在席卷残云。刹那之后,全球科技时钟指针,已经指向人工...

来源:2023.04.13

环球短讯!注意防护!青岛今天受到沙尘回流输送影响,仍有浮尘天气

青岛日报社/观海新闻4月12日讯一场大范围沙尘天气正在影响我国,随着沙尘天气不断向南推进,目前已经影...

来源:2023.04.13

肤色不均怎么调理_肤色不均匀的主要原因:

欢迎观看本篇文章,小勉来为大家解答以上问题。肤色不均怎么调理,肤色不均匀的主要原因:很多人还不知...

来源:2023.04.13

锂电原料暴涨暴跌倒逼产业调整 动力电池退役潮促回收生意大热

近年来,得益于全球绿色低碳转型的大趋势及新能源汽车的快速发展,作为上游的锂电池市场需求增长迅速。...

来源:2023.04.13

【播资讯】aigc概念是什么意思 GraphicalAbstract是什么意思

今天来聊聊关于aigc概念是什么意思,GraphicalAbstract是什么意思的文章,现在就为大家来简单介绍下aig

来源:2023.04.13

【天天播资讯】怎样把记忆力提高 怎么样才能提高记忆力

1、集中注意力八秒钟,当真的需要记住一件事,至少需要集中注意力八秒钟。研究显示大脑将短期记忆转化为...

来源:2023.04.12

全球今亮点!中巴会否就金砖合作的未来发展进行讨论?外交部回应

4月12日,外交部发言人汪文斌主持例行记者会。有记者问,巴西总统卢拉正在中国访问。考虑到巴西是金砖国...

来源:2023.04.12

年增长率近30% 我国算力总规模全球第二

记者4月11日从工信部了解到,近年来,我国算力产业年增长率近30%,算力总规模位居全球第二。工信部相关...

来源:2023.04.12

2023云南楚雄武定罗婺星球音乐节(时间+地点+门票+阵容)

【楚雄彝族自治州】云南武定罗婺星球音乐节演出时间2023 04 21-04 23演出场馆楚雄彝族自治州|武定县...

来源:2023.04.12

新闻快讯

X 关闭

X 关闭

新闻快讯