How to use IHostingEnvironment

前端 未结 1 1940
予麋鹿
予麋鹿 2021-01-01 22:34

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

my Startup.cs:

public Startup(IHostingEnvironmen         


        
相关标签:
1条回答
  • 2021-01-01 22:58

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

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

    where env is the instance passed to the Startup constructor.

    0 讨论(0)
提交回复
热议问题