您可以通过创建自己的实现来解决这个问题。我创建了自己的IWorkingEnvironment 界面,如下所示:
public interface IWorkingEnvironment
{
string EnvironmentName { get; set; }
}
还有我自己的“已知”环境名称:
public static class EnvironmentNames
{
public static readonly string Local = nameof(Local);
public static readonly string Dev = nameof(Dev);
public static readonly string Test = nameof(Test);
public static readonly string Prod = nameof(Prod);
}
接着是IWorkingEnvironment上的扩展方法:
public static class WorkingEnvironmentExtensions
{
public static bool IsLocal(this IWorkingEnvironment environment)
{
return environment.EnvironmentName == EnvironmentNames.Local;
}
public static bool IsDev(this IWorkingEnvironment environment)
{
return environment.EnvironmentName == EnvironmentNames.Dev;
}
// etc...
}
然后我使用 ASP.NET 实现IWorkingEnvironment IHostingEnvironment:
public class AspNetWorkingEnvironment : IWorkingEnvironment
{
private readonly IHostingEnvironment _hostingEnvironment;
public AspNetWorkingEnvironment(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public string EnvironmentName => _hostingEnvironment.EnvironmentName;
}
现在我们要做的就是在我们的依赖注入容器中注册AspNetWorkingEnvironment 作为IWorkingEnvironment 的实现(使用单例生命周期):
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IWorkingEnvironment, AspNetWorkingEnvironment>();
// etc...
}