I find it weird to use context.Server.MapPath
every time just to determine physical location of some known directory/file under app_data folder. I have an understanding that once an application is running, it must not be possible to have its physical location be changed without first shutting it down. If this is true, then I can cache physical path of app_data on application_start and use the cache value for its execution lifetime!
I need experts opinion on this matter. Is my assumption right? there's no possibility of changing the physical path of an application without restarting it, right?
If this is true, It will save me tons of time from having to include context as a parameter in every odd method!
Clarity of the method interface is most important to me, and <context> just doesn't fit into that.
BTW, I'm using shared hosting so I have no control on application physical placement. Does this matt开发者_如何学运维er?
The path is relative to the current request, so MapPath("foo")
might have a different result on requests at different urls. However, if your path is relative to the app-root ("~/foo"
) or relative to the site-root ("/foo"
) you can pretty much cache to your heart's content.
There is perhaps an edge-case scenario of people adding virtual directories inside IIS during execution, but that is vanishingly unlikely, and is pretty-much going to cause pain anyway.
If I were you, I wouldn't cache anything, because I don't believe that caching will make anything faster. or if it was faster, that was about some nano seconds.
about your problem of passing the context, this is because of your design.
I would refactor my code and create a single point which would do IO operation, i.e. an IOHelper class, and I would cache the context there.
I don't think you have to pass the context as a parameter. There is always the possibilty to use
HttpContext.Current.Server.MapPath("~/...");
That's easier than to store the variable in the cache.
Edit: If you really think a call like this would be costly, create a Singleton class Application with a property where you can store the root path, e.g. like this:
public class Application
{
private static string _rootPath = HttpContext.Current.Server.MapPath("~");
public static string RootPath
{
get { return _rootPath; }
}
}
and you can access your Root from everywhere. You can put this code in global.asax as well.
精彩评论