我构建了一个应用程序Asp.net core,我创建了一个.Net core class library单元测试,我想IHostingEnvironment在我的库中使用(用于获取文件的物理路径),所以我将它添加到我的Asp.net核心应用程序服务的startup.cs:
services.AddSingleton<IHostingEnvironment>();
Run Code Online (Sandbox Code Playgroud)
在库中我添加了对我的Asp.net应用程序的引用,并在我的库中的类我写道:
private IHostingEnvironment _env;
public Class1(IHostingEnvironment env)
{
_env = env;
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,它给了我这个错误:
以下构造函数参数没有匹配的fixture日期:IHostingEnvironment env
问题是什么?我该如何使用它.NetCore library?
编辑:我也这样使用:
IServiceCollection services = new ServiceCollection();
services.AddSingleton<IHostingEnvironment>();
IServiceProvider provider = services.BuildServiceProvider();
IHostingEnvironment service = provider.GetService<IHostingEnvironment>();
var p = service.WebRootPath; // give this error: Cannot instantiate implementation type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' for service type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment'
Run Code Online (Sandbox Code Playgroud)
但它也不起作用.
Joe*_*kes 10
注意:services.AddSingleton<IHostingEnvironment>();意味着您正在注册IHostingEnvironment为IHostingEnvironment单例范围内的实现(始终重用)。
由于您无法创建接口的实例,因此会出现此错误。
定义要创建的类(实现IHostingEnvironment),例如:
services.AddSingleton<IHostingEnvironment>(new HostingEnvironment());
Run Code Online (Sandbox Code Playgroud)
在WebHostBuilder构造函数中的第一行是:
this._hostingEnvironment = (IHostingEnvironment) new HostingEnvironment();
Run Code Online (Sandbox Code Playgroud)
该托管环境稍后会由 webhost 构建器填充更多设置。
您应该查看他们的 github 页面或反编译源:https : //github.com/aspnet/Hosting
注意: 的大部分属性/设置HostingEnvironment都Build()在WebHostBuilder. 如果您想自己进行最小起订量/测试,您应该自己设置这些属性,或者也包括WebHostBuilder在您的测试中。
对于我的 .net 类库,我所要做的就是为 2.1.0 版安装以下 nuget 包:
Microsoft.AspNetCore.Hosting.Abstractions
https://www.nuget.org/packages/Microsoft.AspNetCore.Hosting.Abstractions/
然后我只是将 IHostingEnvironment 注入到我的构造函数中。
我什至不需要修改 Startup.cs
| 归档时间: |
|
| 查看次数: |
13867 次 |
| 最近记录: |