如何使用 IHostingEnvironment
接口(interface)而不在构造函数中启动它?
我的 Startup.cs:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
我的课:
public class FileReader
{
// I don't want to initiate within a constructor
public string ReadFile(string fileName)
{
// this is wrong! how can I use it?
var filename = Path.Combine(IHostingEnvironment.WebRootPath, fileName);
}
}
最佳答案
您应该使用集成的依赖注入(inject),因为它使您的代码解耦并且更容易在不破坏内容的情况下进行更改,并且使单元测试变得非常容易。
如果您将通过静态类或方法访问它,那么您的代码将变得难以测试,因为在单元测试中它将始终使用项目路径而不是某些特定的字符串进行测试。
你描述的方式绝对正确,它是不是 错误的!下面只是完整的例子。
public class FileReader
{
private readonly IHostingEnvironment env;
public FileReader(IHostingEnvironment env)
{
if(env==null)
throw new ArgumentNullException(nameof(env));
this.env = env;
}
public string ReadFile(string fileName)
{
var filename = Path.Combine(env.WebRootPath, fileName);
}
}
如果
env
值为 null
在构造函数中,您可能需要自己在 Startup.cs
中注册它,如果 ASP.NET Core 还没有这样做:services.AddSingleton<IHostingEnvironment>(env);
其中 env 是传递给
Startup
的实例构造函数。
关于.net - 如何使用 IHostingEnvironment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40946685/