c# - System.ArgumentNullException : Value cannot be null, 参数名称: implementationInstance

标签 c# iis asp.net-core

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

注意: .net 核心版本 2.0.0

Unhandled Exception: System.ArgumentNullException: Value cannot be null.

Parameter name: implementationInstance

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

I know how the error occurred, how to instantiate?

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;
    }
}

最佳答案

如果有人来寻找可能的解决方案,我可以通过使用 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;
    }
}

关于c# - System.ArgumentNullException : Value cannot be null, 参数名称: implementationInstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47917030/

相关文章:

c# - mvvm - PropertyChanged 不更新带有列表修改的 GUI,但如果我分配一个新列表 - C# silverlight

c# - 从 C# 运行 Powershell 脚本时出错

url - 区分大小写的 URL - 这可以避免吗?

python - 无法让 Mercurial 的 hgweb.cgi 在 IIS7 上工作

macos - 在 ASP.NET Core 中的 Mac Docker 上运行的 SQL Server 的连接字符串是什么?

C# Windows 窗体无法将数据重写到文件

c# - 如何递归地找到对象及其成员使用的所有类型?

.net - 为什么我不能将它添加到 machine.config

c# - ASP.NET Core asp-append-version 属性不适用于 wwwroot 目录之外的静态文件

c# - .NET Core (NET Standard 2.1) 中 DataTable/DataSet 的替换