手动创建 IWebHostEnvironment asp.net core 3.1

Dei*_*kis 7 .net c# asp.net-core asp.net-core-3.1

在 asp.net core 2.1 中,我可以这样创建IHostingEnvironment

public IHostingEnvironment CreateHostingEnvironment()
{
    var hosting = new HostingEnvironment()
    {
       EnvironmentName = "IntegrationTests"
    };
    return hosting;
}
Run Code Online (Sandbox Code Playgroud)

在 Asp.net core 3.1 中,它已更改为IWebHostEnvironment但我需要以类似的方式创建它。可能的目标是创建此对象并设置环境名称。

public IWebHostEnvironment CreateWebHostEnvironment()
{
    var host = new WebHostEnvironment(); // ???
}
Run Code Online (Sandbox Code Playgroud)

mm8*_*mm8 9

唯一的内置实现的的IWebHostEnvironment接口在ASP.NET核心3.X内部:

internal class HostingEnvironment : IHostingEnvironment, Extensions.Hosting.IHostingEnvironment, IWebHostEnvironment
{
    public string EnvironmentName { get; set; } = Extensions.Hosting.Environments.Production;

    public string ApplicationName { get; set; }

    public string WebRootPath { get; set; }

    public IFileProvider WebRootFileProvider { get; set; }

    public string ContentRootPath { get; set; }

    public IFileProvider ContentRootFileProvider { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您出于某种原因需要创建一个实现该接口的类的实例,您基本上可以将上述代码复制到您的项目中,并可能更改类的名称。然后,您可以根据您的要求创建它的实例。

无论如何,框架仅依赖于接口。