1
1
using System ;
2
+ using System . Collections . Concurrent ;
2
3
using System . Collections . Generic ;
3
4
using System . Linq ;
4
5
@@ -9,7 +10,7 @@ namespace Casbin.Rbac
9
10
/// </summary>
10
11
public class Role
11
12
{
12
- private readonly Lazy < Dictionary < string , Role > > _roles = new ( ) ;
13
+ private readonly Lazy < ConcurrentDictionary < string , Role > > _roles = new ( ) ;
13
14
14
15
public Role ( string name )
15
16
{
@@ -28,17 +29,7 @@ public Role(string name, string domain)
28
29
29
30
public void AddRole ( Role role )
30
31
{
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 ) ;
42
33
}
43
34
44
35
public void DeleteRole ( Role role )
@@ -47,11 +38,7 @@ public void DeleteRole(Role role)
47
38
{
48
39
return ;
49
40
}
50
-
51
- if ( _roles . Value . ContainsKey ( role . Name ) )
52
- {
53
- _roles . Value . Remove ( role . Name ) ;
54
- }
41
+ _roles . Value . TryRemove ( role . Name , out _ ) ;
55
42
}
56
43
57
44
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>
71
58
return false ;
72
59
}
73
60
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 ) ) ;
75
63
}
76
64
77
65
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 =
86
74
return _roles . Value . ContainsKey ( name ) ;
87
75
}
88
76
89
-
77
+
90
78
foreach ( var role in _roles . Value . Values )
91
79
{
92
80
if ( name == role . Name || matchingFunc ( role . Name , name ) && role . Name != name )
@@ -101,10 +89,5 @@ public IEnumerable<string> GetRoles()
101
89
{
102
90
return _roles . IsValueCreated ? _roles . Value . Keys : Enumerable . Empty < string > ( ) ;
103
91
}
104
-
105
- public override string ToString ( )
106
- {
107
- return $ "{ Name } { string . Join ( "," , _roles . Value ) } ";
108
- }
109
92
}
110
93
}
0 commit comments