How to access the HttpServerUtility.MapPath method in a Thread or Timer?

前端 未结 6 1910
梦毁少年i
梦毁少年i 2020-12-23 15:46

I use a System.Timers.Timer in my Asp.Net application and I need to use the HttpServerUtility.MapPath method which seems to be only available via <

6条回答
  •  庸人自扰
    2020-12-23 16:32

    HostingEnvironment isn't the perfect solution because it's a very difficult class to mock (see How to unit test code that uses HostingEnvironment.MapPath).

    For those who need testability, a better way might be to create your own path-mapper interface as proposed by https://stackoverflow.com/a/1231962/85196, except implement it as

    public class ServerPathMapper : IPathMapper { 
     public string MapPath(string relativePath) { 
          return HostingEnvironment.MapPath(relativePath); 
     } 
    } 
    

    The result is easily mockable, uses HostingEnvironment internally, and could even potentially address ase69s's concern at the same time.

提交回复
热议问题