技术栈
.net8 web api
AutoMapper
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddAutoMapper(typeof(AutoMapConfig));
using AutoMapper; using jxc.Model; using jxc.ModelDto; namespace jxc.Api.AutoMapExtend; public class AutoMapConfig : Profile { public AutoMapConfig() { CreateMap<InventoryModel, InventoryDto>() .ForMember(c => c.ItemName,s => s.MapFrom(x=>x.ItemName)) .ForMember(c => c.Quantity,s => s.MapFrom(x=>x.Quantity)) .ReverseMap(); } }
AutofacAOP
using Castle.DynamicProxy; using Microsoft.Extensions.Logging; namespace jxcApi.AutofacAOP; public class CustomLogInterceptor : IInterceptor { //支持依赖注入 private readonly ILogger<CustomLogInterceptor> _Logger; public CustomLogInterceptor(ILogger<CustomLogInterceptor> logger) { _Logger = logger; } public void Intercept(IInvocation invocation) { _Logger.LogInformation($"================={invocation.GetType().Name}{invocation.Method.Name}=执行前=================="); invocation.Proceed(); _Logger.LogInformation($"================={invocation.GetType().Name}{invocation.Method.Name}=执行完成=================="); } }
Autofac
//指定Provider的工厂为AutofacServiceProviderFactory builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>(ConfigurationBinder => { //在这里就是可以注册10C中抽象和具体之间的关系 ConfigurationBinder.RegisterType<CustomLogInterceptor>(); ConfigurationBinder.RegisterType<InventoryService>() .EnableClassInterceptors();//aop 扩展 类支持 ConfigurationBinder.RegisterType<InventoryRepository>().As<IInventoryRepository>() .EnableInterfaceInterceptors();//aop 扩展 接口支持 //ConfigurationBinder.RegisterAssemblyTypes(typeof(Program).Assembly) // .Where(t => t.IsSubclassOf(typeof(ControllerBase))) // .PropertiesAutowired() // .EnableClassInterceptors(); }); builder.Services.AddControllers();
freesql
IServiceCollection services = builder.Services; Func<IServiceProvider, IFreeSql> fsqlFactory = r => { IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=freedb2024.db") .UseMonitorCommand(cmd => Console.WriteLine($"Sql:{cmd.CommandText}")) .UseAutoSyncStructure(true) //自动同步实体结构到数据库,只有CRUD时才会生成表 .Build(); return fsql; }; services.AddSingleton<IFreeSql>(fsqlFactory);
Swagger 显示控制器层注释
builder.Services.AddSwaggerGen(option => { var file = Path.Combine(AppContext.BaseDirectory, $"{AppDomain.CurrentDomain.FriendlyName}.xml"); option.IncludeXmlComments(file, true); //true:显示控制器层注释 });
log4net
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Logging.AddLog4Net("log4net.Config");标签:前后,builder,分离,public,Services,invocation,using,ConfigurationBinder,搭建 From: https://www.cnblogs.com/hlm750908/p/18660602