Home > Software engineering >  how does IServiceScopeFactory get registered internally?
how does IServiceScopeFactory get registered internally?

Time:07-08

below is some code example using DI:

public class Program {
   public static void Main(string[] args) {
      var services = new ServiceCollection();                

      services.AddScoped<IXXX, XXX>();    
 
      ServiceProvider rootContainer = services.BuildServiceProvider(true);    

      using (IServiceScope scope = rootContainer.CreateScope) { /
         IXXX sth= scope.ServiceProvider.GetRequiredService<XXX>();  
      }
   }
}

and the source code of CreateScope() is

public static class ServiceProviderServiceExtensions {
   // ...
   public static IServiceScope CreateScope(this IServiceProvider provider) {
      return provider.GetRequiredService<IServiceScopeFactory>().CreateScope();   
   }
}

how does IServiceScopeFactory get registered? and what is the concrete implementation for IServiceScopeFactory?

CodePudding user response:

how does IServiceScopeFactory get registered?

It is registered internally within the ServiceProvider when it is initialised.

//...

CallSiteFactory.Add(typeof(IServiceScopeFactory), new ConstantCallSite(typeof(IServiceScopeFactory), Root));

//...

Source

and what is the concrete implementation for IServiceScopeFactory?

In the above registration, the Root is a property

internal ServiceProviderEngineScope Root { get; }

Source

of the internal type ServiceProviderEngineScope

internal sealed class ServiceProviderEngineScope : IServiceScope, IServiceProvider, IAsyncDisposable, IServiceScopeFactory

Source

  • Related