'IHostingEnvironment' 已过时

'IHostingEnvironment' is obsolete

我将 ASP.NET Core 项目更新为 .NET Core v3.0.0-preview3,我现在得到:

Startup.cs(75,50,75,69): warning CS0618: 'IHostingEnvironment' is obsolete: 'This type is obsolete and will be removed in a future version. The recommended alternative is Microsoft.AspNetCore.Hosting.IWebHostEnvironment.'

密码是:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
  if (env.IsDevelopment()) {
    …
  }
}

现在正确的做法是什么?是否有任何文档或示例可以证明这一点?

When Microsoft.Extensions.Hosting was introduced in 2.1 some types like IHostingEnvironment and IApplicationLifetime were copied from Microsoft.AspNetCore.Hosting. Some 3.0 changes cause apps to include both the Microsoft.Extensions.Hosting and Microsoft.AspNetCore.Hosting namespaces. Any use of those duplicate types causes an "ambiguous reference" compiler error when both namespaces are referenced.

This error has been addressed in 3.0.0-preview3 by marking the following types obsolete and replacing them with new types. There have not been any behavioral changes made for the new types, only naming.

Obsolete types (warning):

Microsoft.Extensions.Hosting.IHostingEnvironment
Microsoft.AspNetCore.Hosting.IHostingEnvironment
Microsoft.Extensions.Hosting.IApplicationLifetime
Microsoft.AspNetCore.Hosting.IApplicationLifetime
Microsoft.Extensions.Hosting.EnvironmentName
Microsoft.AspNetCore.Hosting.EnvironmentName

New types:

Microsoft.Extensions.Hosting.IHostEnvironment
Microsoft.AspNetCore.Hosting.IWebHostEnvironment : IHostEnvironment
Microsoft.Extensions.Hosting.IHostApplicationLifetime
Microsoft.Extensions.Hosting.Environments

Note the new IHostEnvironment IsDevelopment, IsProduction, etc. extension methods are in the Microsoft.Extensions.Hosting namespace which may need to be added to your app.

For 3.0 both the old and new types will be available from HostBulder's and WebHostBuilder's dependency injection containers. The old types will be removed in 4.0.

来源:https://github.com/aspnet/AspNetCore/issues/7749

总而言之,您现在正在寻找 IWebHostEnvironment。您可能还需要添加 using for Microsoft.Extensions.Hosting

似乎 IHostingEnvironment 已被 IHostEnvironment(以及其他一些)取代。 您应该能够更改代码中的接口类型,一切都会像以前一样工作:-)

您可以在 GitHub 上的 link 找到有关更改的更多信息 https://github.com/aspnet/AspNetCore/issues/7749

编辑 还有一个附加接口 IWebHostEnvironment 可用于 ASP.NET 核心应用程序。这在 Microsoft.AspNetCore.Hosting 命名空间中可用。

对于env.IsDevelopment(),我使用了env.EnvironmentName.Equals("Development")

来自 ASP.NET Core 5,使用:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    if (Environments.Development.Equals(env.EnvironmentName))
    {
        ...