11using System ;
2+ using System . Collections . Concurrent ;
23using System . Collections . Generic ;
34using System . Linq ;
45
@@ -9,7 +10,7 @@ namespace Casbin.Rbac
910 /// </summary>
1011 public class Role
1112 {
12- private readonly Lazy < Dictionary < string , Role > > _roles = new ( ) ;
13+ private readonly Lazy < ConcurrentDictionary < string , Role > > _roles = new ( ) ;
1314
1415 public Role ( string name )
1516 {
@@ -28,17 +29,7 @@ public Role(string name, string domain)
2829
2930 public void AddRole ( Role role )
3031 {
31- if ( _roles . IsValueCreated is false )
32- {
33- _roles . Value . Add ( role . Name , role ) ;
34- }
35-
36- if ( _roles . Value . ContainsKey ( role . Name ) )
37- {
38- return ;
39- }
40-
41- _roles . Value . Add ( role . Name , role ) ;
32+ _roles . Value . TryAdd ( role . Name , role ) ;
4233 }
4334
4435 public void DeleteRole ( Role role )
@@ -47,11 +38,7 @@ public void DeleteRole(Role role)
4738 {
4839 return ;
4940 }
50-
51- if ( _roles . Value . ContainsKey ( role . Name ) )
52- {
53- _roles . Value . Remove ( role . Name ) ;
54- }
41+ _roles . Value . TryRemove ( role . Name , out _ ) ;
5542 }
5643
5744 public bool HasRole ( string name , int hierarchyLevel , Func < string , string , bool > matchingFunc = null )
@@ -71,7 +58,8 @@ public bool HasRole(string name, int hierarchyLevel, Func<string, string, bool>
7158 return false ;
7259 }
7360
74- return _roles . Value . Values . Any ( role => role . HasRole ( name , hierarchyLevel - 1 ) ) ;
61+ return _roles . Value . Values . Any ( role =>
62+ role . HasRole ( name , hierarchyLevel - 1 ) ) ;
7563 }
7664
7765 public bool HasDirectRole ( string name , Func < string , string , bool > matchingFunc = null )
@@ -86,7 +74,7 @@ public bool HasDirectRole(string name, Func<string, string, bool> matchingFunc =
8674 return _roles . Value . ContainsKey ( name ) ;
8775 }
8876
89-
77+
9078 foreach ( var role in _roles . Value . Values )
9179 {
9280 if ( name == role . Name || matchingFunc ( role . Name , name ) && role . Name != name )
@@ -101,10 +89,5 @@ public IEnumerable<string> GetRoles()
10189 {
10290 return _roles . IsValueCreated ? _roles . Value . Keys : Enumerable . Empty < string > ( ) ;
10391 }
104-
105- public override string ToString ( )
106- {
107- return $ "{ Name } { string . Join ( "," , _roles . Value ) } ";
108- }
10992 }
11093}
0 commit comments