伙伴云客服论坛»论坛 S区 S生产制造 查看内容

0 评论

0 收藏

分享

【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用

文章目录

    前言一、Autofac的使用
      1.装置包2.效劳注入3.AddModule扩展方法详解
        3.1 AppSetting.Init
          3.1.1 数据库字符串加/解密
        3.2 Autofac相关效劳类
          3.2.1 UserContext3.2.2 ActionObserver3.2.3 ObjectModelValidatorState





前言

IoC容器是一种设计形式,它可以管理应用程序中的对象依赖关系。它可以自动创建和注入对象,从而减少了代码的耦合度和反复性。
Autofac是Microsoft .NET的IoC容器。它管理类之间的依赖关系,以便应用程序在大小和复杂性增加时易于更改。这是通过将常规 .NET 类视为组件来实现的。
Autofac的官网:https://autofac.org/

【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-1.png


Autofac的源码网址:https://gitee.com/dennisdyh/Autofac.Extensions.DependencyInjection

【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-2.png


一、Autofac的使用

1.装置包
  1. Autofac.Extensions.DependencyInjection
复制代码
【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-3.png


2.效劳注入

在Program注入Autofac效劳
  1. publicstaticIHostBuilderCreateHostBuilder(string[] args)=>
  2.        Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>{
  3.                webBuilder.ConfigureKestrel(serverOptions =>{
  4.                    serverOptions.Limits.MaxRequestBodySize =10485760;// Set properties and call methods on options});
  5.                webBuilder.UseKestrel().UseUrls("http://*:9991");
  6.                webBuilder.UseIIS();
  7.                webBuilder.UseStartup<Startup>();}).UseServiceProviderFactory(newAutofacServiceProviderFactory());//设置工厂来交换实例
复制代码
【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-4.png

在Startup中增加ConfigureContainer方法,用来配置映射关系
  1. publicvoidConfigureContainer(ContainerBuilder builder){
  2.     Services.AddModule(builder, Configuration);}
复制代码
使用了Autofac以后,在IServiceCollection中注入的效劳,也能生效;因为Autofac是先接受了所有的来自于IServiceCollection的效劳映射后,再去读取ConfigureContainer方法中配置的映射。

【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-5.png


3.AddModule扩展方法详解

AddModule包含了反射注入容器和一堆效劳注入容器
  1. //  private static bool _isMysql = false;publicstaticIServiceCollectionAddModule(thisIServiceCollection services,ContainerBuilder builder,IConfiguration configuration){//services.AddSession();//services.AddMemoryCache();//初始化配置文件
  2.     AppSetting.Init(services, configuration);Type baseType =typeof(IDependency);var compilationLibrary = DependencyContext.Default
  3.         .RuntimeLibraries
  4.         .Where(x =>!x.Serviceable
  5.         && x.Type =="project").ToList();var count1 = compilationLibrary.Count;List<Assembly> assemblyList =newList<Assembly>();foreach(var _compilation in compilationLibrary){try{
  6.             assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(newAssemblyName(_compilation.Name)));}catch(Exception ex){
  7.             Console.WriteLine(_compilation.Name + ex.Message);}}
  8.     builder.RegisterAssemblyTypes(assemblyList.ToArray()).Where(type => baseType.IsAssignableFrom(type)&&!type.IsAbstract).AsSelf().AsImplementedInterfaces().InstancePerLifetimeScope();
  9.     builder.RegisterType<UserContext>().InstancePerLifetimeScope();
  10.     builder.RegisterType<ActionObserver>().InstancePerLifetimeScope();//model校验结果
  11.     builder.RegisterType<ObjectModelValidatorState>().InstancePerLifetimeScope();string connectionString = DBServerProvider.GetConnectionString(null);if(DBType.Name == DbCurrentType.MySql.ToString()){//增加dapper对mysql字段Guid映射
  12.         SqlMapper.AddTypeHandler(newDapperParseGuidTypeHandler());
  13.         SqlMapper.RemoveTypeMap(typeof(Guid?));//services.AddDbContext<SysDbContext>();//mysql8.x的版本使用Pomelo.EntityFrameworkCore.MySql 3.1会产生异常,需要在字符串连接上添加allowPublicKeyRetrieval=true
  14.         services.AddDbContextPool<SysDbContext>(optionsBuilder =>{ optionsBuilder.UseMySql(connectionString);},64);
  15.         services.AddDbContextPool<ServiceDbContext>(optionsBuilder =>{ optionsBuilder.UseMySql(connectionString);},64);
  16.         services.AddDbContextPool<ReportDbContext>(optionsBuilder =>{ optionsBuilder.UseMySql(connectionString);},64);}elseif(DBType.Name == DbCurrentType.PgSql.ToString()){
  17.         services.AddDbContextPool<SysDbContext>(optionsBuilder =>{ optionsBuilder.UseNpgsql(connectionString);},64);
  18.         services.AddDbContextPool<ServiceDbContext>(optionsBuilder =>{ optionsBuilder.UseNpgsql(connectionString);},64);
  19.         services.AddDbContextPool<ReportDbContext>(optionsBuilder =>{ optionsBuilder.UseNpgsql(connectionString);},64);}else{
  20.         services.AddDbContextPool<SysDbContext>(optionsBuilder =>{ optionsBuilder.UseSqlServer(connectionString);},64);
  21.         services.AddDbContextPool<ServiceDbContext>(optionsBuilder =>{ optionsBuilder.UseSqlServer(connectionString);},64);
  22.         services.AddDbContextPool<ReportDbContext>(optionsBuilder =>{ optionsBuilder.UseSqlServer(connectionString);},64);}//启用缓存if(AppSetting.UseRedis){
  23.         builder.RegisterType<RedisCacheService>().As<ICacheService>().SingleInstance();}else{
  24.         builder.RegisterType<MemoryCacheService>().As<ICacheService>().SingleInstance();}//kafka注入//if (AppSetting.Kafka.UseConsumer)//    builder.RegisterType<KafkaConsumer<string, string>>().As<IKafkaConsumer<string, string>>().SingleInstance();//if (AppSetting.Kafka.UseProducer)//    builder.RegisterType<KafkaProducer<string, string>>().As<IKafkaProducer<string, string>>().SingleInstance();return services;}
复制代码
【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-6.png


3.1 AppSetting.Init

应用程序初始化主要是对配置文件使用
  1. {"Logging":{"LogLevel":{"Default":"Information","Microsoft":"Warning","Microsoft.Hosting.Lifetime":"Information"}},"AllowedHosts":"*","VirtualPath":{"StaticFile":"E:\\Web\\Static",//配置的虚拟目录文件所在途径"FolderName":"/Static"//访问时此途径时的别名},"AppUrls":{},"Connection":{"DBType":"MsSql",//MySql/MsSql/PgSql  //数据库类型,假设使用的是sqlserver此处应设置为MsSql//sqlserver连接字符串"DbConnectionString":"Data Source=.;Initial Catalog=iMES_Open;Persist Security Info=True;User ID=sa;Password=1;Connect Timeout=500;",//mysql连接字符串(晋级EFCore3.1到时已将mysql连接字符串修改,2019-12-20)//"DbConnectionString": " Data Source=127.0.0.1;Database=imes_open;AllowLoadLocalInfile=true;User ID=root;Password=123456;allowPublicKeyRetrieval=true;pooling=true;CharSet=utf8;port=3306;sslmode=none;",//PgSql连接字符串//  "DbConnectionString": "Host=132.232.2.109;Port=5432;User id=postgres;password=jxx_abcd;Database=netcoredev;","RedisConnectionString":"127.0.0.1,Password=123456,SyncTimeout=15000",//redis连接字符串(最好加密)"UseRedis":"false",//是否使用redis,假设不使用,默认使用Memory内置缓存"UseSignalR":"true"//是否使用SignalR(2022.05.03),注意需要将端的地址配置到下面的CorsUrls属性中},//业务数据库连接"ServiceConnectingString":"Data Source=.;Initial Catalog=iMES;Persist Security Info=True;User ID=sa;Password=123456;Connect Timeout=500;",//报表数据库连接"ReportConnectingString":"Data Source=.;Initial Catalog=iMES;Persist Security Info=True;User ID=sa;Password=123456;Connect Timeout=500;","Secret":{//秘钥配置"JWT":"BB3647441FFA4B5DB4E64A29B53CE525",//JWT"Audience":"iMES.core","Issuer":"iMES.core.owner","User":"C5ABA9E202D94C43A3CA66002BF77FAF",//"DB":"3F8B7B38AD3D484A89ACA513CBD79F36","Redis":"E6D90DDBC70C4F4EA3C312B6FCB473C8"},//================跨域恳求 (CORS)配置(2019-12-20新增),//================.netcore3.1必需配置此属性,多个url用豆号隔开,url为vue站点的地址,可以将发布后的地址也同时配置上"CorsUrls":"http://localhost:8081,http://localhost:8082,http://localhost:8080,http://localhost:7080,http://localhost:9980,http://127.0.0.1:9980,http://localhost:9990,http://www.volcore.xyz,http://app.625sc.com,https://imes.625sc.com","ExpMinutes":"120",//JWT有效期(分钟=默认120),"CreateMember":{//对表插入数据时,需要记录创建人/创建时间/创建日期,配置UserIdField/UserNameField/DateField分别为对应数据库的创建人CreateID,创建人Creator,创建时间CreateDate字段(新建数据时,由框架默认完成给这几个字段赋值,字段区分大小写)或可手动调用T.SetCreateDefaultVal()完成设置创建人/创建时间/创建日期//假设表的主键是GUID,界面查询时默认会用到DateField对应的实体(数据库)字段停止排序"UserIdField":"CreateID","UserNameField":"Creator","DateField":"CreateDate"},"ModifyMember":{//修改同上"UserIdField":"ModifyID","UserNameField":"Modifier","DateField":"ModifyDate"},//演示系统过滤Action,只要超级管理员才干操作,其他用户只要只读权限"GlobalFilter":{"Message":"演示环境,当前帐号没有开启此功能权限","Enable":"false",//开启Action过滤"Actions":["Update","Del","Add","SavePermission","Save","CreatePage","CreateVuePage","CreateEntityModel","SaveEidt","CreateServices","Import","Upload","Audit","ModifyPwd"]},"Kafka":{//是否使用消费者"UseProducer":false,"ProducerSettings":{"BootstrapServers":"192.168.20.241:9092",//confluent cloud bootstrap servers"SaslMechanism":"Plain","SecurityProtocol":"SaslSsl","SaslUsername":"<confluent cloud key>","SaslPassword":"<confluent cloud secret>"},//是否使用消费者"UseConsumer":false,//是否持续监听消费者订阅 用于while循环订阅"IsConsumerSubscribe":true,"ConsumerSettings":{"BootstrapServers":"192.168.20.241:9092",//confluent cloud bootstrap servers"GroupId":"amcl_group",//web-example-group"SaslMechanism":"Plain","SecurityProtocol":"SaslSsl","SaslUsername":"<confluent cloud key>","SaslPassword":"<confluent cloud secret>"},"Topics":{"TestTopic":"alarm_topic"}},"Mail":{"Address":"zm_rid@163.com",//发件的邮箱"Host":"smtp.163.com","Name":"iMES",//发送人名称"Port":25,"EnableSsl":false,"AuthPwd":"受权密码"//受权密码(对应邮箱设置里面去开启)},"QuartzAccessKey":"65EC9387312E4717810C552963CE59FF",//定时任务的值"ExportPDFPath":"C:\\iMES_Open\\iMES_Front\\PDF"//导出PDF途径}
复制代码
【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-7.png

  1. publicstaticvoidInit(IServiceCollection services,IConfiguration configuration){//---------------------------------配置信息效劳类的映射------------------------------
  2.     Configuration = configuration;
  3.     services.Configure<Secret>(configuration.GetSection("Secret"));
  4.     services.Configure<Connection>(configuration.GetSection("Connection"));
  5.     services.Configure<CreateMember>(configuration.GetSection("CreateMember"));
  6.     services.Configure<ModifyMember>(configuration.GetSection("ModifyMember"));
  7.     services.Configure<GlobalFilter>(configuration.GetSection("GlobalFilter"));
  8.     services.Configure<Kafka>(configuration.GetSection("Kafka"));//---------------------------------获取当前程序目录-----------------------------------var provider = services.BuildServiceProvider();IWebHostEnvironment environment = provider.GetRequiredService<IWebHostEnvironment>();
  9.     CurrentPath = Path.Combine(environment.ContentRootPath,"").ReplacePath();//---------------------------------获取各种配置操作类-------------------------------------
  10.     Secret = provider.GetRequiredService<IOptions<Secret>>().Value;//设置修改或删除时需要设置为默认用户信息的字段
  11.     CreateMember = provider.GetRequiredService<IOptions<CreateMember>>().Value ??newCreateMember();
  12.     ModifyMember = provider.GetRequiredService<IOptions<ModifyMember>>().Value ??newModifyMember();//全局过滤行为
  13.     GlobalFilter = provider.GetRequiredService<IOptions<GlobalFilter>>().Value ??newGlobalFilter();
  14.     GlobalFilter.Actions = GlobalFilter.Actions ??newstring[0];//Kafka消息队列
  15.     Kafka = provider.GetRequiredService<IOptions<Kafka>>().Value ??newKafka();//各种数据库和缓存数据库连接字符串
  16.     _connection = provider.GetRequiredService<IOptions<Connection>>().Value;//JWT过期时间
  17.     ExpMinutes =(configuration["ExpMinutes"]??"120").GetInt();//判断数据库是否存在
  18.     DBType.Name = _connection.DBType;if(string.IsNullOrEmpty(_connection.DbConnectionString))thrownewSystem.Exception("未配置好数据库默认连接");//停止数据库解密(解密失败返回原字符串,胜利返回新字符串)try{
  19.         _connection.DbConnectionString = _connection.DbConnectionString.DecryptDES(Secret.DB);}catch{}if(!string.IsNullOrEmpty(_connection.RedisConnectionString)){try{
  20.             _connection.RedisConnectionString = _connection.RedisConnectionString.DecryptDES(Secret.Redis);}catch{}}}
复制代码
【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-8.png


3.1.1 数据库字符串加/解密
  1. publicstaticclassSecurityEncDecryptExtensions{privatestaticbyte[] Keys ={0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F};/// <summary> /// DES加密字符串 /// </summary> /// <param name="encryptString">待加密的字符串</param> /// <param name="encryptKey">加密密钥,要求为16位</param> /// <returns>加密胜利返回加密后的字符串,失败返回源串</returns> publicstaticstringEncryptDES(thisstring encryptString,string encryptKey){try{byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0,16));byte[] rgbIV = Keys;byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);using(var DCSP = Aes.Create()){using(MemoryStream mStream =newMemoryStream()){using(CryptoStream cStream =newCryptoStream(mStream, DCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write)){
  2.                         cStream.Write(inputByteArray,0, inputByteArray.Length);
  3.                         cStream.FlushFinalBlock();return Convert.ToBase64String(mStream.ToArray()).Replace('+','_').Replace('/','~');}}}}catch(Exception ex){thrownewException("密码加密异常"+ ex.Message);}}/// <summary> /// DES解密字符串 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <param name="decryptKey">解密密钥,要求为16位,和加密密钥相同</param> /// <returns>解密胜利返回解密后的字符串,失败返源串</returns> publicstaticstringDecryptDES(thisstring decryptString,string decryptKey){byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0,16));byte[] rgbIV = Keys;byte[] inputByteArray = Convert.FromBase64String(decryptString.Replace('_','+').Replace('~','/'));using(var DCSP = Aes.Create()){using(MemoryStream mStream =newMemoryStream()){using(CryptoStream cStream =newCryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write)){byte[] inputByteArrays =newbyte[inputByteArray.Length];
  4.                     cStream.Write(inputByteArray,0, inputByteArray.Length);
  5.                     cStream.FlushFinalBlock();return Encoding.UTF8.GetString(mStream.ToArray());}}}}publicstaticboolTryDecryptDES(thisstring decryptString,string decryptKey,outstring result){
  6.         result ="";try{
  7.             result =DecryptDES(decryptString, decryptKey);returntrue;}catch{returnfalse;}}}
复制代码
【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-9.png


3.2 Autofac相关效劳类

3.2.1 UserContext

UserContext主要作用就是记录用户信息
  1. publicclassUserContext{/// <summary>/// 为了尽量减少redis或Memory读取,保证执行效率,将UserContext注入到DI,/// 每个UserContext的属性至多读取一次redis或Memory缓存从而进步查询效率/// </summary>publicstaticUserContext Current
  2.     {get{return Context.RequestServices.GetService(typeof(UserContext))asUserContext;}}privatestaticMicrosoft.AspNetCore.Http.HttpContext Context
  3.     {get{return Utilities.HttpContext.Current;}}privatestaticICacheService CacheService
  4.     {get{returnGetService<ICacheService>();}}privatestaticTGetService<T>()whereT:class{return AutofacContainerModule.GetService<T>();}publicUserInfo UserInfo
  5.     {get{if(_userInfo !=null){return _userInfo;}returnGetUserInfo(UserId);}}privateUserInfo _userInfo {get;set;}/// <summary>/// 角色ID为1的默认为超级管理员/// </summary>publicbool IsSuperAdmin
  6.     {get{returnIsRoleIdSuperAdmin(this.RoleId);}}/// <summary>/// 角色ID为1的默认为超级管理员/// </summary>publicstaticboolIsRoleIdSuperAdmin(int roleId){return roleId ==1;}publicUserInfoGetUserInfo(int userId){if(_userInfo !=null)return _userInfo;if(userId <=0){
  7.             _userInfo =newUserInfo();return _userInfo;}string key = userId.GetUserIdKey();
  8.         _userInfo = CacheService.Get<UserInfo>(key);if(_userInfo !=null&& _userInfo.User_Id >0)return _userInfo;
  9.         _userInfo = DBServerProvider.DbContext.Set<Sys_User>().Where(x => x.User_Id == userId).Select(s =>newUserInfo(){
  10.                 User_Id = userId,
  11.                 Role_Id = s.Role_Id.GetInt(),
  12.                 RoleName = s.RoleName,//2022.08.15增加部门id
  13.                 DeptId = s.Dept_Id??0,
  14.                 Token = s.Token,
  15.                 UserName = s.UserName,
  16.                 UserTrueName = s.UserTrueName,
  17.                 Enable = s.Enable
  18.             }).FirstOrDefault();if(_userInfo !=null&& _userInfo.User_Id >0){
  19.             CacheService.AddObject(key, _userInfo);}return _userInfo ??newUserInfo();}/// <summary>/// 获取角色权限时通过安全字典锁定的角色id/// </summary>privatestaticConcurrentDictionary<string,object> objKeyValue =newConcurrentDictionary<string,object>();/// <summary>/// 角色权限的版本号/// </summary>privatestaticreadonlyDictionary<int,string> rolePermissionsVersion =newDictionary<int,string>();/// <summary>/// 每个角色ID对应的菜单权限(已做静态化处置)/// 每次获取权限时用当前效劳器的版本号与redis/memory缓存的版本比较,假设不同会重新刷新缓存/// </summary>privatestaticreadonlyDictionary<int, List<Permissions>> rolePermissions =newDictionary<int, List<Permissions>>();/// <summary>/// 获取用户所有的菜单权限/// </summary>publicList<Permissions> Permissions
  20.     {get{returnGetPermissions(RoleId);}}/// <summary>/// 菜单按钮变卦时,同时刷新权限缓存2022.05.23/// </summary>/// <param name="menuId"></param>publicvoidRefreshWithMenuActionChange(int menuId){foreach(var roleId in rolePermissions.Where(c => c.Value.Any(x => x.Menu_Id == menuId)).Select(s => s.Key)){if(rolePermissionsVersion.ContainsKey(roleId)){
  21.                 CacheService.Add(roleId.GetRoleIdKey(), DateTime.Now.ToString("yyyyMMddHHMMssfff"));}}}/// <summary>/// 获取单个表的权限/// </summary>/// <param name="tableName"></param>/// <returns></returns>publicPermissionsGetPermissions(string tableName){returnGetPermissions(RoleId).Where(x => x.TableName == tableName).FirstOrDefault();}/// <summary>/// 2022.03.26/// 菜单类型1:挪动端,0:PC端/// </summary>publicstaticint MenuType
  22.     {get{return Context.Request.Headers.ContainsKey("uapp")?1:0;}}/// <summary>/// 自定条件查询权限/// </summary>/// <param name="func"></param>/// <returns></returns>publicPermissionsGetPermissions(Func<Permissions,bool> func){// 2022.03.26增挪动端加菜单类型判断returnGetPermissions(RoleId).Where(func).Where(x => x.MenuType == MenuType).FirstOrDefault();}privateList<Permissions>ActionToArray(List<Permissions> permissions){
  23.         permissions.ForEach(x =>{try{var menuAuthArr = x.MenuAuth.DeserializeObject<List<Sys_Actions>>();
  24.                 x.UserAuthArr =string.IsNullOrEmpty(x.UserAuth)?newstring[0]: x.UserAuth.Split(",").Where(c => menuAuthArr.Any(m => m.Value == c)).ToArray();}catch{}finally{if(x.UserAuthArr ==null){
  25.                     x.UserAuthArr =newstring[0];}}});return permissions;}privateList<Permissions>MenuActionToArray(List<Permissions> permissions){
  26.         permissions.ForEach(x =>{try{
  27.                 x.UserAuthArr =string.IsNullOrEmpty(x.UserAuth)?newstring[0]: x.UserAuth.DeserializeObject<List<Sys_Actions>>().Select(s => s.Value).ToArray();}catch{}finally{if(x.UserAuthArr ==null){
  28.                     x.UserAuthArr =newstring[0];}}});return permissions;}publicList<Permissions>GetPermissions(int roleId){if(IsRoleIdSuperAdmin(roleId)){//2020.12.27增加菜单界面上不显示,但可以分配权限var permissions = DBServerProvider.DbContext.Set<Sys_Menu>().Where(x => x.Enable ==1|| x.Enable ==2).Select(a =>newPermissions{
  29.                     Menu_Id = a.Menu_Id,
  30.                     ParentId = a.ParentId,//2020.05.06增加默认将表名转换成小写,权限验证时不再转换
  31.                     TableName =(a.TableName ??"").ToLower(),//MenuAuth = a.Auth,
  32.                     UserAuth = a.Auth,// 2022.03.26增挪动端加菜单类型
  33.                     MenuType = a.MenuType ??0}).ToList();returnMenuActionToArray(permissions);}ICacheService cacheService = CacheService;string roleKey = roleId.GetRoleIdKey();//角色有缓存,并且当前效劳器的角色版本号与redis/memory缓存角色的版本号相同直接返回静态对象角色权限string currnetVeriosn ="";if(rolePermissionsVersion.TryGetValue(roleId,out currnetVeriosn)&& currnetVeriosn == cacheService.Get(roleKey)){return rolePermissions.ContainsKey(roleId)? rolePermissions[roleId]:newList<Permissions>();}//锁定每个角色,通过安全字典减少锁粒度,否则多个同时角色获取缓存会导致阻塞object objId = objKeyValue.GetOrAdd(roleId.ToString(),newobject());//锁定每个角色lock(objId){if(rolePermissionsVersion.TryGetValue(roleId,out currnetVeriosn)&& currnetVeriosn == cacheService.Get(roleKey)){return rolePermissions.ContainsKey(roleId)? rolePermissions[roleId]:newList<Permissions>();}//没有redis/memory缓存角色的版本号或与当前效劳器的角色版本号不同时,刷新缓存var dbContext = DBServerProvider.DbContext;List<Permissions> _permissions =(from a in dbContext.Set<Sys_Menu>()join b in dbContext.Set<Sys_RoleAuth>()on a.Menu_Id equals b.Menu_Id
  34.                                               whereb.Role_Id == roleId //&& a.ParentId > 0&& b.AuthValue !=""orderby a.ParentId
  35.                                               selectnewPermissions{
  36.                                                   Menu_Id = a.Menu_Id,
  37.                                                   ParentId = a.ParentId,//2020.05.06增加默认将表名转换成小写,权限验证时不再转换
  38.                                                   TableName =(a.TableName ??"").ToLower(),
  39.                                                   MenuAuth = a.Auth,
  40.                                                   UserAuth = b.AuthValue ??"",// 2022.03.26增挪动端加菜单类型
  41.                                                   MenuType = a.MenuType ??0}).ToList();ActionToArray(_permissions);string _version = cacheService.Get(roleKey);//生成一个唯一版本号标识if(_version ==null){
  42.                 _version = DateTime.Now.ToString("yyyyMMddHHMMssfff");//将版本号写入缓存
  43.                 cacheService.Add(roleKey, _version);}//刷新当前效劳器角色的权限
  44.             rolePermissions[roleId]= _permissions;//写入当前效劳器的角色最新版本号
  45.             rolePermissionsVersion[roleId]= _version;return _permissions;}}/// <summary>/// 判断是否有权限/// </summary>/// <param name="tableName"></param>/// <param name="authName"></param>/// <param name="roleId"></param>/// <returns></returns>publicboolExistsPermissions(string tableName,string authName,int roleId =0){if(roleId <=0) roleId = RoleId;
  46.         tableName = tableName.ToLower();returnGetPermissions(roleId).Any(x => x.TableName == tableName && x.UserAuthArr.Contains(authName));}/// <summary>/// 判断是否有权限/// </summary>/// <param name="tableName"></param>/// <param name="authName"></param>/// <param name="roleId"></param>/// <returns></returns>publicboolExistsPermissions(string tableName,ActionPermissionOptions actionPermission,int roleId =0){returnExistsPermissions(tableName, actionPermission.ToString(), roleId);}publicint UserId
  47.     {get{return(Context.User.FindFirstValue(JwtRegisteredClaimNames.Jti)?? Context.User.FindFirstValue(ClaimTypes.NameIdentifier)).GetInt();}}publicstring UserName
  48.     {get{return UserInfo.UserName;}}publicstring UserTrueName
  49.     {get{return UserInfo.UserTrueName;}}publicstring Token
  50.     {get{return UserInfo.Token;}}publicint RoleId
  51.     {get{return UserInfo.Role_Id;}}publicvoidLogOut(int userId){
  52.         CacheService.Remove(userId.GetUserIdKey());}}
复制代码
【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-10.png


3.2.2 ActionObserver

ActionObserver记录Action执行的信息
  1. publicclassActionObserver{//public ActionObserver(IHttpContextAccessor httpContextAccessor)//{//    this.RequestDate = DateTime.Now;//    this.HttpContext = httpContextAccessor.HttpContext;//}/// <summary>/// 记录action执行的开端时间/// </summary>publicDateTime RequestDate {get;set;}/// <summary>/// 当前恳求是否已经写过日志,防止手动与系统自动反复写日志/// </summary>publicbool IsWrite {get;set;}publicHttpContext HttpContext {get;}}
复制代码
【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-11.png


3.2.3 ObjectModelValidatorState

ObjectModelValidatorState 对象模型校验效劳
  1. publicclassObjectModelValidatorState{publicObjectModelValidatorState(){this.Status =true;}publicbool Status {get;set;}publicbool HasModelContent {get;set;}publicstring Code {get;set;}publicstring Message {get;set;}}publicclassObjectValidatorResult{publicObjectValidatorResult(){}publicObjectValidatorResult(bool status){this.Status = status;}publicObjectValidatorResultOK(string message){this.Status =true;this.Message = message;returnthis;}publicObjectValidatorResultError(string message){this.Status =false;this.Message = message;returnthis;}publicbool Status {get;set;}publicstring Message {get;set;}}
复制代码
【愚公系列】2023年03月 MES消费制造执行系统-001.Autofac的使用-12.png


其实在Autofac中还注入了数据库效劳,下一章讲解。

回复

举报 使用道具

相关帖子
全部回复
暂无回帖,快来参与回复吧
本版积分规则 高级模式
B Color Image Link Quote Code Smilies

梦魇绽荼蘼
注册会员
主题 22
回复 19
粉丝 0
|网站地图
快速回复 返回顶部 返回列表