ASP.NET 5 MVC 6 DI:ServiceProvider无法解析类型

时间:2015-09-15 11:20:14

标签: c# dependency-injection asp.net-core asp.net-core-mvc

在下面的代码中,serviceProvider.GetService<DocumentDbConnection>()正在解析为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));
}

为什么会这样?该类型是在调用GetService之前注册的,所以如果不解析为单例?

1 个答案:

答案 0 :(得分:12)

您在注册DocumentDbConnection之前构建服务提供商。您应该首先注册您需要的服务。然后BuildServiceProvider将构建一个服务提供商,其服务已注册到那时:

services.AddSingleton<DocumentDbConnection>(x => new DocumentDbConnection(uri, authKey));
var serviceProvider = services.BuildServiceProvider();

// code using serviceProvider