Skip to content

IHostingEnvironment Updates #157

@JunTaoLuo

Description

@JunTaoLuo

As part of our update to IHostingEnvironment we have made the following changes:

  • Added ApplicationName, ContentRootPath and ContentRootFileProvider.
  • Removed Configuration and MapPath(string virtualPath)

We aim to relocate the information we provided from IApplicationEnvironment to IHostingEnvironment. This means that the fields on IApplicationEnvironment, specifically ApplicationName and ApplicationBasePath, will no longer be set. Instead, the ApplicationName will be set on the IHostingEnvironment, the application base path is stored in the ContentRootPath field and the ContentRootFileProvider is the file provider for the directory set by ContentRootPath. The extension method to configure the content root is also renamed to UseContentRoot(...).

All code using IApplicationEnvironment.ApplicationBasePath should be changed to use IHostingEnvironment.ContentRootPath.

All code using IApplicationEnvironment.ApplicationName should be changed to use IHostingEnvironment.ApplicationName

MapPath should be replaced by looking at the appropriate IFileProvider calls (see below).

For example, previously it would be:

var host = new WebHostBuilder()
    .UseApplicationBasePath("/path/to/content")
    ...
    .Build();
...
var applicationEnvironment = host.Services.GetService<IApplicationEnvironment>();
var applicationName = applicationEnvironment.ApplicationName;
var applicationBasePath = applicationEnvironment.ApplicationBasePath;

Now, it should be changed to:

var host = new WebHostBuilder()
    .UseContentRoot("/path/to/content")
    ...
    .Build();
...
var hostingEnvironment = host.Services.GetService<IHostingEnvironment>();
var applicationName = hostingEnvironment.ApplicationName;
var contentRootPath = hostingEnvironment.ContentRootPath;

Old (hostingEnvironment is IHostingEnvironment). The old MapPath method only worked with files inside of the webroot. To get files on the ContentRoot (where the application code and views lived) required more steps.

var pathInsideWebRoot = hostingEnvironment.MapPath("/foo");

IHostingEnvironment now has 2 IFileProvider types exposed:

var fileInfoInsideWebRoot = hostingEnvironment.WebRootFileProvider.GetFileInfo("/foo");
var fileInfoInsideContentRoot = hostingEnvironment.ContentRootFileProvider.GetFileInfo("/foo");

var pathInsideWebRoot = fileInfoInsideWebRoot.PhysicalPath;
var pathInsideContentRoot = fileInfoInsideContentRoot.PhysicalPath;

Use aspnet/Hosting#651 for further discussions.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions