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

标签 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 之前注册被调用所以它不应该解析为单例吗?

最佳答案

您在注册 DocumentDbConnection 之前构建服务提供者。您应该首先注册您需要的服务。然后 BuildServiceProvider 将使用之前注册的服务构建一个服务提供者:

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

// code using serviceProvider

关于c# - ASP.NET 5 MVC 6 DI : ServiceProvider not resolving type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32584695/

相关文章:

design-patterns - 依赖注入(inject)和服务定位器模式之间有什么区别?

java - Tapestry 5 和具有相同接口(interface)的 Spring bean

c# - 从 .NET Core Program.cs 访问配置

asp.net-core - Visual Studio 2017 安装破坏了 Visual Studio 2015 ASP.NET Core 项目

java - Dagger 2 单例不工作

c# - 列宽的数据注释

c# - 将 Linq 查询与 Entity Framework 一起使用时引发异常

c# - View 模型应该包含记录器吗?

c# - AddSingleton<TService, TImplementation>() 的工作原理

c# - Android - Java/c#/c++ 速度