手动创建 IWebHostEnvironment asp.net 核心 3.1

Creating IWebHostEnvironment manually asp.net core 3.1

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

public IHostingEnvironment CreateHostingEnvironment()
{
    var hosting = new HostingEnvironment()
    {
       EnvironmentName = "IntegrationTests"
    };
    return hosting;
}

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

public IWebHostEnvironment CreateWebHostEnvironment()
{
    var host = new WebHostEnvironment(); // ???
}

IWebHostEnvironment接口的唯一内置implementation在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; }
}

因此,如果出于某种原因需要创建实现接口的 class 实例,基本上只需将上述代码复制到您的项目中,或许可以更改 class 的名称].然后您可以根据您的要求创建它的实例。

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