55using System . Reflection ;
66using System . Runtime . CompilerServices ;
77using Autofac . Core . Resolving . Pipeline ;
8+ using Autofac . Diagnostics ;
89using Autofac . Util ;
910using Autofac . Util . Cache ;
1011
@@ -50,6 +51,7 @@ internal class DefaultRegisteredServicesTracker : Disposable, IRegisteredService
5051
5152 private Dictionary < Service , ServiceRegistrationInfo > ? _ephemeralServiceInfo ;
5253 private bool _trackerPopulationComplete ;
54+ private int _registrationsVersion ;
5355
5456 /// <summary>
5557 /// Initializes a new instance of the <see cref="DefaultRegisteredServicesTracker"/> class.
@@ -75,6 +77,9 @@ public DefaultRegisteredServicesTracker()
7577 /// </summary>
7678 public event EventHandler < IRegistrationSource > ? RegistrationSourceAdded ;
7779
80+ /// <inheritdoc/>
81+ public int RegistrationsVersion => Volatile . Read ( ref _registrationsVersion ) ;
82+
7883 /// <inheritdoc />
7984 public IEnumerable < IComponentRegistration > Registrations
8085 {
@@ -138,6 +143,8 @@ public virtual void AddRegistration(IComponentRegistration registration, bool pr
138143 registration . BuildResolvePipeline ( this ) ;
139144 }
140145 }
146+
147+ Interlocked . Increment ( ref _registrationsVersion ) ;
141148 }
142149
143150 /// <inheritdoc />
@@ -315,6 +322,7 @@ private ServiceRegistrationInfo GetInitializedServiceInfo(Service service)
315322 }
316323
317324 var info = GetServiceInfo ( service ) ;
325+ var instrumentationService = AutofacMetrics . Enabled ? service . ToString ( ) : null ;
318326 if ( info . IsInitialized )
319327 {
320328 return info ;
@@ -339,7 +347,13 @@ private ServiceRegistrationInfo GetInitializedServiceInfo(Service service)
339347 var shouldProcessCompletion = false ;
340348 try
341349 {
342- Monitor . Enter ( info , ref lockTaken ) ;
350+ Monitor . TryEnter ( info , ref lockTaken ) ;
351+ if ( ! lockTaken )
352+ {
353+ var wait = ValueStopwatch . StartNew ( ) ;
354+ Monitor . Enter ( info , ref lockTaken ) ;
355+ AutofacLockMetrics . RecordContention ( "Service" , instrumentationService , wait . ElapsedTicks ) ;
356+ }
343357
344358 if ( info . IsInitialized )
345359 {
0 commit comments