依赖注入
由容器统一创建对象并管理其创建对象的生命周期;
AddTransient瞬时服务
每次使用都会创建新的实例
AddScoped作用域
容器或子容器的生命周期内,对象保持一致,如果容器释放掉,那就意味着对象也会释放掉;
AddSingleton单例
整个根容器的生命周期内是同一个对象
其他
TryAddScoped
AddHttpClient
AddHttpContextAccessor
AddDbContext
AddControllers
批量注入
其他生命周期中获取服务
中间件
系统自带
UseHttpsRedirection:强制https跳转
....
用途:
1全局拦截,如:IP白名单,请求头过滤
2错误处理,如:未处理异常处理、自定义异常(登录失败,参数错误等)处理
3权限校验
4。。。
配置文件application.json
读取方式:
1Configuration["A"]
2Configuration["A:b"]
3Configuration.GetValue<int>("A")
4Configuration.GetConnectionString
5Configuration.Get<TOption>
选项模式
IOptions、IOptionsMonitor以及IOptionsSnapshot的区别
配置项目启动地址
1修改launchSettings.json
2builder.WebHost.UseUrls("http://0.0.0.0:5552", "https://127.0.0.1:5553", "https://localhost:5554")
WebApi
ActionResult返回类型
return result;
return Ok(result);//200
return BadRequest(result);/400
CORS允许跨域请求
每次使用都会创建新的实例
容器或子容器的生命周期内,对象保持一致,如果容器释放掉,那就意味着对象也会释放掉;
整个根容器的生命周期内是同一个对象
TryAddScoped
AddHttpClient
AddHttpContextAccessor
AddDbContext
AddControllers
批量注入
var assembly = Assembly.GetExecutingAssembly(); var ilist = assembly.GetTypes().Where(t => t.GetTypeInfo().IsInterface); var list = assembly.GetTypes().Where(t => t.GetTypeInfo().IsClass); foreach (Type serviceType in list) { var interfaceType = ilist.FirstOrDefault(x => x.IsAssignableFrom(serviceType)); if (interfaceType != null) { if (interfaceType.FullName != null && interfaceType.FullName.StartsWith("KKBM.Application.Queries")) { services.AddScoped(interfaceType, serviceType); } } }
UseHttpsRedirection:强制https跳转
....
1全局拦截,如:IP白名单,请求头过滤
2错误处理,如:未处理异常处理、自定义异常(登录失败,参数错误等)处理
3权限校验
4。。。
1Configuration["A"]
2Configuration["A:b"]
3Configuration.GetValue<int>("A")
4Configuration.GetConnectionString
5Configuration.Get<TOption>
1修改launchSettings.json
2builder.WebHost.UseUrls("http://0.0.0.0:5552", "https://127.0.0.1:5553", "https://localhost:5554")
return result;
return Ok(result);//200
return BadRequest(result);/400
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!