Search code examples
c#.netasp.net-coreasp.net-core-3.1

Creating IWebHostEnvironment manually asp.net core 3.1


In asp.net core 2.1 I could create IHostingEnvironment like this:

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

In Asp.net core 3.1 it was changed to IWebHostEnvironment but I need to create it similar way. My goal is to create this object and set the environment name.

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

Solution

  • The only built-in implementation of the IWebHostEnvironment interface is internal in ASP.NET Core 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; }
    }
    

    So if you need to create an instance of a class that implements the interface for some reason, you could basically just copy the above code into your project and perhaps change the name of the class. You can then create instances of it as per your requirements.

    The framework depends on the interface only anyway.