@@ -12,7 +12,7 @@ sealed class TokenProviderFactory : ITokenProviderFactory
1212 {
1313 private readonly IServiceProvider serviceProvider ;
1414 private readonly TokenProviderFactoryOptions options ;
15- private readonly ConcurrentDictionary < Type , ITokenProvider > tokenProviderCache = new ConcurrentDictionary < Type , ITokenProvider > ( ) ;
15+ private readonly ConcurrentDictionary < CacheKey , ITokenProvider > tokenProviderCache = new ConcurrentDictionary < CacheKey , ITokenProvider > ( ) ;
1616
1717 /// <summary>
1818 /// 默认的token提供者工厂
@@ -40,15 +40,28 @@ public ITokenProvider Create(Type httpApiType, TypeMatchMode typeMatchMode)
4040 throw new ArgumentNullException ( nameof ( httpApiType ) ) ;
4141 }
4242
43+ var cacheKey = new CacheKey ( httpApiType , typeMatchMode ) ;
44+ return this . tokenProviderCache . GetOrAdd ( cacheKey , this . GetTokenProvider ) ;
45+ }
46+
47+ /// <summary>
48+ /// 获取或创建其对应的token提供者
49+ /// </summary>
50+ /// <param name="cacheKey">缓存的键</param>
51+ /// <returns></returns>
52+ /// <exception cref="InvalidOperationException"></exception>
53+ private ITokenProvider GetTokenProvider ( CacheKey cacheKey )
54+ {
55+ var httpApiType = cacheKey . HttpApiType ;
4356 if ( this . options . TryGetValue ( httpApiType , out var serviceType ) )
4457 {
4558 var service = this . serviceProvider . GetRequiredService ( serviceType ) ;
4659 return ( ( ITokenProviderService ) service ) . TokenProvider ;
4760 }
4861
49- if ( typeMatchMode == TypeMatchMode . TypeOrBaseTypes )
62+ if ( cacheKey . TypeMatchMode == TypeMatchMode . TypeOrBaseTypes )
5063 {
51- return this . tokenProviderCache . GetOrAdd ( httpApiType , GetTokenProviderFromBaseType ) ;
64+ return this . GetTokenProviderFromBaseType ( httpApiType ) ;
5265 }
5366
5467 throw new InvalidOperationException ( $ "尚未注册{ httpApiType } 的token提供者") ;
@@ -72,5 +85,36 @@ private ITokenProvider GetTokenProviderFromBaseType(Type httpApiType)
7285 }
7386 throw new InvalidOperationException ( $ "尚未注册{ httpApiType } 或其基础接口的token提供者") ;
7487 }
88+
89+ /// <summary>
90+ /// 缓存的键
91+ /// </summary>
92+ private class CacheKey : IEquatable < CacheKey >
93+ {
94+ public Type HttpApiType { get ; }
95+
96+ public TypeMatchMode TypeMatchMode { get ; }
97+
98+ public CacheKey ( Type httpApiType , TypeMatchMode typeMatchMode )
99+ {
100+ this . HttpApiType = httpApiType ;
101+ this . TypeMatchMode = typeMatchMode ;
102+ }
103+
104+ public bool Equals ( CacheKey other )
105+ {
106+ return this . HttpApiType == other . HttpApiType && this . TypeMatchMode == other . TypeMatchMode ;
107+ }
108+
109+ public override bool Equals ( object obj )
110+ {
111+ return obj is CacheKey other && this . Equals ( other ) ;
112+ }
113+
114+ public override int GetHashCode ( )
115+ {
116+ return HashCode . Combine ( this . HttpApiType , this . TypeMatchMode ) ;
117+ }
118+ }
75119 }
76120}
0 commit comments