Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 5 MVC 6 DI: ServiceProvider not resolving type

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?

like image 205
Dave New Avatar asked Sep 15 '15 11:09

Dave New


People also ask

How can dependency injection be resolved?

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.

What is the difference between Addsingleton and Addscoped?

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.

When should I use IServiceProvider?

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.

How do I get IServiceCollection from IServiceProvider?

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.


1 Answers

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
like image 109
Henk Mollema Avatar answered Sep 22 '22 14:09

Henk Mollema