如何使用IHostingEnvironment [英] How to use IHostingEnvironment

查看:743
本文介绍了如何使用IHostingEnvironment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 IHostingEnvironment 接口而不在构造函数中启动它?

How do I use the IHostingEnvironment interface without initiating it in a constructor?

我的Startup.cs:

my 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); 
    }
}


推荐答案

您应该使用集成的依赖注入,因为它可以使您的代码解耦,并且更容易更改而又不会破坏内容,并使单元测试变得非常容易。

You should use the integrated dependency injection as it makes your code decoupled and easier to change without breaking stuff and make it very easy to unit test.

如果要通过静态访问它类或方法,那么您的代码将变得难以测试,因为在单元测试中,它将始终使用项目路径而不是某些特定的字符串进行测试。

If you would access it via static class or method, then your code becomes hard to test as in unit test it would always use the project path and not some specific string for testing.

您所说的方式绝对正确,是错误的!下面只是完整的示例。

The way you described it absolutely correct and it's NOT wrong! Below just the complete example.

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尚未这样做:

If the env value is null in the constructor, you may need to register it yourself in Startup.cs, if ASP.NET Core doesn't do it already:

services.AddSingleton<IHostingEnvironment>(env);

其中env是传递给 Startup 构造函数。

where env is the instance passed to the Startup constructor.

这篇关于如何使用IHostingEnvironment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆