简体   繁体   English

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

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

In the code below, serviceProvider.GetService<DocumentDbConnection>() is resolving to null : 在下面的代码中, 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));
}

Why is this happening? 为什么会这样? The type is being registered before GetService is called so should it not resolve to the singleton? 在调用GetService之前注册了类型,所以它是否应该解析为单例?

You are building the service provider before you register the DocumentDbConnection . 注册DocumentDbConnection 之前,您正在构建服务提供者。 You should register the services you need first. 您应该首先注册您需要的服务。 Then BuildServiceProvider will build a service provider with the services registered until then: 然后, BuildServiceProvider将构建一个服务提供者,其中注册的服务在此之前:

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

// code using serviceProvider

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM