Dave New
Dave New

Reputation: 40042

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?

Upvotes: 8

Views: 2314

Answers (1)

Henk Mollema
Henk Mollema

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

Related Questions