我在 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/