ASP.NET 5 MVC 6 DI: ServiceProvider does not allow type

In the code below, serviceProvider.GetService<DocumentDbConnection>() resolves to null :

 public void ConfigureService(IServiceCollection services) { var serviceProvider = services.BuildServiceProvider(); services.AddSingleton<DocumentDbConnection>( x => new DocumentDbConnection(uri, authKey)); // service is null? var connection = serviceProvider.GetService<DocumentDbConnection>(); services.AddTransient<IStopRepository, StopRepository>( x => new StopRepository(connection, databaseId, collectionId)); } 

Why is this happening? GetService type registered before GetService is called so that it does not allow singleton?

+8
c # dependency-injection asp.net-core asp.net-core-mvc
source share
1 answer

You create a service provider before registering DocumentDbConnection . You must first register the services you need. Then BuildServiceProvider build a service provider with previously registered services:

 services.AddSingleton<DocumentDbConnection>(x => new DocumentDbConnection(uri, authKey)); var serviceProvider = services.BuildServiceProvider(); // code using serviceProvider 
+11
source share

All Articles