Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.ArgumentNullException: Value cannot be null, Parameter name: implementationInstance

I deployed .NET core mvc application in IIS, when I run app, the page show 502.5 error, I run command in powershell "dotnet D:\deploy\WebApp\WebApp.dll" ,this follow show detail error content:

NOTE:.net core version 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;
    }
}
like image 622
Lin.Hao Avatar asked Nov 08 '22 12:11

Lin.Hao


1 Answers

In case someone comes along looking for a possible solution, I was able to resolve this issue in a .NET Core 3.1 project by getting the configuration using the IServiceProvider callback provided by .AddSingleton in the following way:

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;
    }
}
like image 83
eakosin Avatar answered Nov 15 '22 06:11

eakosin