66using Autofac . Core . Activators . Delegate ;
77using Autofac . Core . Registration ;
88using Autofac . Util ;
9+ using Autofac . Util . Cache ;
910
1011namespace Autofac . Features . KeyedServices ;
1112
@@ -14,6 +15,17 @@ namespace Autofac.Features.KeyedServices;
1415/// </summary>
1516internal sealed class AnyKeyRegistrationSource : IRegistrationSource
1617{
18+ private readonly ReflectionCacheKeyedServiceDictionary < IComponentRegistration [ ] > _adapterCache ;
19+
20+ /// <summary>
21+ /// Initializes a new instance of the <see cref="AnyKeyRegistrationSource"/> class.
22+ /// </summary>
23+ public AnyKeyRegistrationSource ( )
24+ {
25+ _adapterCache = ReflectionCacheSet . Shared . GetOrCreateCache < ReflectionCacheKeyedServiceDictionary < IComponentRegistration [ ] > > ( nameof ( AnyKeyRegistrationSource ) ) ;
26+ _adapterCache . Usage = ReflectionCacheUsage . Resolution ;
27+ }
28+
1729 /// <inheritdoc/>
1830 public bool IsAdapterForIndividualComponents => true ;
1931
@@ -37,6 +49,11 @@ public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Fun
3749 return Enumerable . Empty < IComponentRegistration > ( ) ;
3850 }
3951
52+ if ( _adapterCache . TryGetValue ( keyedService , out var cached ) )
53+ {
54+ return cached ;
55+ }
56+
4057 // If there are already specific registrations for this key, do nothing.
4158 if ( registrationAccessor ( service ) . Any ( ) )
4259 {
@@ -51,7 +68,14 @@ public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Fun
5168 return Enumerable . Empty < IComponentRegistration > ( ) ;
5269 }
5370
54- return anyKeyRegistrations . Select ( r => CreateAdapterRegistration ( r , keyedService ) ) ;
71+ var adapters = new IComponentRegistration [ anyKeyRegistrations . Length ] ;
72+ for ( var i = 0 ; i < anyKeyRegistrations . Length ; i ++ )
73+ {
74+ adapters [ i ] = CreateAdapterRegistration ( anyKeyRegistrations [ i ] , keyedService ) ;
75+ }
76+
77+ _adapterCache . TryAdd ( keyedService , adapters ) ;
78+ return adapters ;
5579 }
5680
5781 private static ComponentRegistration CreateAdapterRegistration ( ServiceRegistration anyKeyRegistration , KeyedService requestedService )
0 commit comments