Reputation: 40042
In the code below, serviceProvider.GetService<DocumentDbConnection>()
is resolving 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? The type is being registered before GetService
is called so should it not resolve to the singleton?
Upvotes: 8
Views: 2314
Reputation: 46571
You are building the service provider before you register the DocumentDbConnection
. You should register the services you need first. Then BuildServiceProvider
will build a service provider with the services registered until then:
services.AddSingleton<DocumentDbConnection>(x => new DocumentDbConnection(uri, authKey));
var serviceProvider = services.BuildServiceProvider();
// code using serviceProvider
Upvotes: 12