.Net 6中将appsettings.json配置项注入到services层
![](https://img2022.cnblogs.com/blog/1686412/202207/1686412-20220701183810734-493778614.png)
1 namespace Entity.Common 2 { 3 /// <summary> 4 /// 生源费审核设置 5 /// </summary> 6 public class SalarySyOptions 7 { 8 public int SalaryItemId { get; set; }//生源费项目ID 9 } 10 }
1 { 2 "SalarySy": { 3 "SalaryItemId": "38" //生源费id 4 }, 5 "Salary": { 6 "Upondate": "2021-12-01 00:00:00" //绩效工资生效日期 7 }, 8 "AllowedHosts": "*" 9 }
1 public static void AddCustomServices(this IServiceCollection Services,IConfiguration configuration) 2 { 3 Services.AddOptions(); 4 Services.Configure<SalarySyOptions>(configuration.GetSection("SalarySy"));//添加生源费审核salaryitemid配置,读取appsetting.json文件 5 Services.Configure<SalaryOptions>(configuration.GetSection("Salary"));//添加绩效工资生效日期配置。 6 } 7 这个类是builder.Services的扩展方法,在program.cs中加入下面代码即可 8 builder.Services.AddCustomServices(builder.Configuration);//添加用户服务注入(扩展方法)
1 namespace Services 2 { 3 public class AuditSyService 4 { 5 private readonly IRepository<ModelAudit3> _audit3; 6 private readonly SalarySyOptions _salarysyoptions;//生源费审核配置注入 7 8 public AuditSyService(IRepository<ModelSalarySy> salarySys,IRepository<ModelAudit3>audit3,IOptions<SalarySyOptions>salarysyoptions) 9 { 10 _audit3 = audit3; 11 _salarysyoptions = salarysyoptions.Value; 12 } 13 14 /// <summary> 15 /// 新增生源费审核记录 16 /// </summary> 17 /// <param name="stuid">学员id</param> 18 /// <param name="enroll_id">招生人id</param> 19 /// <param name="salaryitemid">工资标准id</param> 20 /// <param name="userid">操作用户id</param> 21 /// <param name="username">操作用户名称</param> 22 /// <returns></returns> 23 public int AddSalarySy(int stuid, int enroll_id,int userid,string username) 24 { 25 return _audit3.Add(new ModelAudit3 { StuId=stuid,Enroll_id=enroll_id,SalaryItemId=_salarysyoptions.SalaryItemId,Sdate=DateTime.Now,UserId=userid,Optman=username}); 26 } 27 } 28 }