Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. May goal is to create this object and set Environment name.

public IWebHostEnvironment CreateWebHostEnvironment()
{
    var host = new WebHostEnvironment(); // ???
}
like image 906
Deivydas Voroneckis Avatar asked Mar 27 '20 09:03

Deivydas Voroneckis


People also ask

What is IWebHostEnvironment in .NET Core?

IWebHostEnvironment Provides information about the web hosting environment an application is running in. belongs to namespace Microsoft.AspNetCore.Hosting. The IWebHostEnvironment interface need to be injected as dependency in the Controller and then later used throughout the Controller.

Where is the Wwwroot folder in ASP.NET Core?

The path of the wwwroot folder is accessed using the interfaces IHostingEnvironment (. Net Core 2.0) and IWebHostEnvironment (. Net Core 3.0) in ASP.Net Core. The IHostingEnvironment is an interface for .


1 Answers

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.

like image 163
mm8 Avatar answered Oct 18 '22 06:10

mm8