关于C#:手动创建IWebHostEnvironment asp.net core 3.1

Creating IWebHostEnvironment manually asp.net core 3.1

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

1
2
3
4
5
6
7
8
public IHostingEnvironment CreateHostingEnvironment()
{
    var hosting = new HostingEnvironment()
    {
       EnvironmentName ="IntegrationTests"
    };
    return hosting;
}

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

1
2
3
4
public IWebHostEnvironment CreateWebHostEnvironment()
{
    var host = new WebHostEnvironment(); // ???
}


IWebHostEnvironment接口的唯一内置实现在ASP.NET Core 3.x中是内部的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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; }
}

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

该框架仍然只依赖于接口。