我用Asp core构建一个应用程序,并创建一个.Net core class library用于单元测试,我想在我的库中使用IHostingEnvironment(用于获取文件的物理路径),因此我将其添加到启动中.我的Asp核心应用程序服务的CS:
I build an application with Asp core, and i create a .Net core class library for unit testing, i want to use IHostingEnvironment in my library(for get physical path of a file ), so i added this to startup.cs of my Asp Core application Service:
services.AddSingleton<IHostingEnvironment>();在库中,我添加了对Asp应用程序的引用,在库中的类中,我写了:
and in Library i added reference to my Asp application, and in my class in library i write:
private IHostingEnvironment _env; public Class1(IHostingEnvironment env) { _env = env; }但是当我运行它时,它给了我这个错误:
but when i run it, it gives me this error:
以下构造函数参数的夹具日期不匹配:IHostingEnvironment env
the following constructor parameters did not have matching fixture date : IHostingEnvironment env
出什么问题了?我如何在.NetCore library中使用它?
what is the problem? how can i use it in .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'但它也不起作用.
推荐答案注意:services.AddSingleton<IHostingEnvironment>();表示您正在单例范围内注册IHostingEnvironment作为IHostingEnvironment的实现(始终重用).
Note: services.AddSingleton<IHostingEnvironment>(); means you are registering IHostingEnvironment as an implementation for IHostingEnvironment in a singleton scope (always reuse).
由于无法创建接口的实例,因此会出现此错误.
Since you can't create an instance of an interface, you get this error.
定义要创建的类(实现IHostingEnvironment),例如:
define the class you want to be created (that implements IHostingEnvironment), eg:
services.AddSingleton<IHostingEnvironment>(new HostingEnvironment());背后的dotnet核心(托管nuget程序包)
在WebHostBuilder中,构造函数的第一行是:
Behind the scenes dotnet core (Hosting nuget package)
In the WebHostBuilder The first row in the constructor is:
this._hostingEnvironment = (IHostingEnvironment) new HostingEnvironment();此主机托管环境随后由Webhost构建器填充了更多设置.
This hosting environment is later filled with more settings, by the webhost builder.
您应该查看其github页面或反编译源代码: github/aspnet/Hosting
You should look at their github page or decompile the sources: github/aspnet/Hosting
注意:HostingEnvironment的大多数属性/设置是在WebHostBuilder的Build()方法上设置的.如果您想自己进行定量/测试,则应自行设置这些属性,或者也可以在测试中加入WebHostBuilder.
Note: Most of the properties/settings of HostingEnvironment are set on Build() method of the WebHostBuilder. If you want to moq/test this yourself you should set these properties yourself or just also include the WebHostBuilder in your test.
更多推荐
在.NetCore库中使用IHostingEnvironment
发布评论