System.ArgumentNullException:值不能为空,参数名称: implementationInstance

Lin*_*Hao 5 c# iis asp.net-core

我在 IIS 中部署了 .NET core mvc 应用程序,当我运行应用程序时,页面显示 502.5 错误,我在 powershell "dotnet D:\deploy\WebApp\WebApp.dll" 中运行命令,下面显示详细的错误内容:

注意: .net 核心版本 2.0.0

未处理的异常:System.ArgumentNullException:值不能为空。

参数名称: implementationInstance

在 Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions
.AddSingleton[TService](IServiceCollection services, TService implementationInstance)

我知道错误是如何发生的,如何实例化?

public class Startup
{   ...
    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSingleton(CreateQuery());  // this is error location
        ...
    }

    IQuery CreateQuery()
    {
        IQuery query = null;
        var dataBase = Configuration.GetSection("AppSettings")["DataBase"];
        var defaultConnection = Configuration.GetSection("ConnectionStrings")["SqlServer"];
        switch (dataBase)
        {
            case "sqlserver":
                query = new WebApp.Query.Query(defaultConnection);
                break;
        }
        return query;
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 2

如果有人来寻找可能的解决方案,我可以通过使用以下方式IServiceProvider提供的回调获取配置来解决 .NET Core 3.1 项目中的此问题:.AddSingleton

public class Startup
{   ...
    public void ConfigureServices(IServiceCollection services)
    {
        ...
        // Pass the service provider that AddSingleton provides
        services.AddSingleton((serviceProvider) => {
            CreateQuery(serviceProvider)
        });
        ...
    }

    IQuery CreateQuery(IServiceProvider serviceProvider)
    {
        IQuery query = null;

        // Use the service provider to get the configuration
        var configuration = serviceProvider.GetRequiredService<IConfiguration>();

        var dataBase = configuration.GetSection("AppSettings")["DataBase"];
        var defaultConnection = configuration.GetSection("ConnectionStrings")["SqlServer"];
        switch (dataBase)
        {
            case "sqlserver":
                query = new WebApp.Query.Query(defaultConnection);
                break;
        }
        return query;
    }
}
Run Code Online (Sandbox Code Playgroud)