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?
Resolve dependencies using IServiceProvider You can use the IServiceCollection interface to create a dependency injection container. Once the container has been created, the IServiceCollection instance is composed into an IServiceProvider instance. You can use this instance to resolve services.
Singleton is a single instance for the lifetime of the application domain. Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET. Transient is a single instance per code request.
The IServiceProvider is responsible for resolving instances of types at runtime, as required by the application. These instances can be injected into other services resolved from the same dependency injection container. The ServiceProvider ensures that resolved services live for the expected lifetime.
An instance of IServiceProvider itself can be obtained by calling a BuildServiceProvider method of an IServiceCollection. IServiceCollection is a parameter of ConfigureServices method in a Startup class. It seems to be magically called with an instance of IServiceCollection by the framework.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With