关于c#:在.NetCore库中使用IHostingEnvironment

Using IHostingEnvironment in .NetCore library

我构建一个ASP.NET Core应用程序,并创建一个.NET Core类库以进行单元测试。

我想在我的库中使用IHostingEnvironment(以获取文件的物理路径),因此我已将此行添加到ASP.NET Core应用程序的Startup.cs中:

1
services.AddSingleton<IHostingEnvironment>();

我在库中添加了对我的ASP.NET应用程序的引用,在我的班级中,我这样写:

1
2
3
4
5
private IHostingEnvironment _env;
public Class1(IHostingEnvironment env)
{
    _env = env;
}

但是当我运行它时,它给了我这个错误:

the following constructor parameters did not have matching fixture date : IHostingEnvironment env

出什么问题了?
如何在.NET Core类库中使用它?

编辑:我也尝试使用它:

1
2
3
4
5
IServiceCollection services = new ServiceCollection();
services.AddSingleton<IHostingEnvironment>();
IServiceProvider provider = services.BuildServiceProvider();
IHostingEnvironment service = provider.GetService<IHostingEnvironment>();
var p = service.WebRootPath;

最后一个给我这个错误:

Cannot instantiate implementation type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' for service type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment'


注意:services.AddSingleton<IHostingEnvironment>();表示您正在单例范围内注册IHostingEnvironment作为IHostingEnvironment的实现(始终重用)。

由于无法创建接口的实例,因此会出现此错误。

定义要创建的类(实现IHostingEnvironment),例如:

1
services.AddSingleton<IHostingEnvironment>(new HostingEnvironment());

dotnet核心背后(托管nuget包)

WebHostBuilder中,构造函数的第一行是:

1
this._hostingEnvironment = (IHostingEnvironment) new HostingEnvironment();

稍后,Webhost构建器将在此托管环境中填充更多设置。

您应该查看他们的github页面或反编译源代码:https://github.com/aspnet/Hosting

注意:HostingEnvironment的大多数属性/设置是在WebHostBuilderBuild()方法上设置的。如果要自己进行定量/测试,则应自行设置这些属性,或者也可以在测试中包括WebHostBuilder


对于我的.net类库,我要做的就是为版本2.1.0安装以下nuget软件包:

Microsoft.AspNetCore.Hosting.Abstractions

https://www.nuget.org/packages/Microsoft.AspNetCore.Hosting.Abstractions/

,然后将IHostingEnvironment注入到我的构造函数中。

我什至不需要修改Startup.cs


我在这里结束时的参考注释。

如果您在类库中定位netstandard(netstandard2.0),请从NuGet添加Microsoft.Extensions.Hosting.Abstractions以获取IHostingEnvironment接口,而无需任何实现。

我知道问题还是要指定.net核心。..可能会帮助那些人在我身旁。


这在.net核心类库和控制台应用程序中对我都有效:

使用参考,

1
2
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;

添加DI注册,

1
services.AddSingleton<IHostingEnvironment, HostingEnvironment>();

尝试一下,它很简单

1
2
3
4
5
6
7
8
9
private IHostEnvironment env;
public Startup(IHostEnvironment env)
{
    this.env = env;
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHostEnvironment>(env);
}

然后您可以在类上使用它

1
2
3
4
5
private IHostingEnvironment _env;
public Class1(IHostingEnvironment env)
{
    _env = env;
}

希望它能完成工作^ _ ^