Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将System.IServiceProvider类型隐式转换为ServiceProvider_C#_Asp.net Core_.net Core - Fatal编程技术网

C# 无法将System.IServiceProvider类型隐式转换为ServiceProvider

C# 无法将System.IServiceProvider类型隐式转换为ServiceProvider,c#,asp.net-core,.net-core,C#,Asp.net Core,.net Core,如何在测试项目中从Startup类获取服务?下面是接收铸造错误 var test = new WebHostBuilder() .UseContentRoot("C:\\APITest\\APITest.WebAPI") .UseEnvironment("Development") .UseConfiguration(new ConfigurationBuilder() .SetBas

如何在测试项目中从Startup类获取服务?下面是接收铸造错误

        var test = new WebHostBuilder()
           .UseContentRoot("C:\\APITest\\APITest.WebAPI")
           .UseEnvironment("Development")
           .UseConfiguration(new ConfigurationBuilder()
               .SetBasePath("C:\\APITest\\APITest.WebAPI")
               .AddJsonFile("appsettings.json")
               .Build())
               .UseStartup<Startup>()
           .Build();

        ServiceProvider =  test.Services;
var test=new WebHostBuilder()
.UseContentRoot(“C:\\APITest\\APITest.WebAPI”)
.环境(“发展”)
.UseConfiguration(新的ConfigurationBuilder()
.SetBasePath(“C:\\APITest\\APITest.WebAPI”)
.AddJsonFile(“appsettings.json”)
.Build())
.UseStartup()
.Build();
ServiceProvider=test.Services;
无法将类型“System.IServiceProvider”隐式转换为 “Microsoft.Extensions.DependencyInjection.ServiceProvider”。一 存在显式转换(是否缺少强制转换?)

这是一个案例。有两种类型的强制转换,隐式和显式。作为强类型,C#对于隐式转换非常保守。如果不是的话,我们最终会以失败告终。因此,如果你决定是否真的想冒险,它更倾向于你

消息很清楚:您有一个类型为
System.IServiceProvider
的变量,并尝试将其分配到只接受
Microsoft.Extensions.DependencyInjection.ServiceProvider
的变量或参数。将
ServiceProvider
强制转换为
IServiceProvider
将隐式进行。反过来说?没有


这是一种有点奇怪的情况——因为大多数参数和字段/属性往往是接口或抽象基类。这样你就可以对你所接受的更加宽容。您很少看到使用具体的类。如果这是您的代码,您可能希望更改它。如果没有,你就得冒着显式强制转换的风险,希望一切顺利。

看起来你的类将ServiceProvider定义为一个具体的类。将其更改为定义为接口

...
// this is wrong
ServiceProvider ServiceProvider;

// this is right
IServiceProvider ServiceProvider;

这很清楚。它不会尝试隐式地强制转换它,但如果您确定了某些类型,则只需显式地强制转换它。