I have a library code, which should be aware whether it is executed in the context of a web server or standalone application server.
The obvious that comes to mind i
Gets a value that specifies whether the current Windows Presentation Foundation (WPF) application is browser hosted.
Thats how its done in XBAP
or if you have an appdomain do reflection and get something from it? using
I think the very best thing to do is to split up the library into 2 dlls, one that's truly generic, and one (the one that requires ASP.NET) that only gets loaded in the website. Checking if it's currently running in ASP.NET feels like a bit of a hack.
Ofcourse it depends on the situation wether or not you can easily do this.
Trying to solve another problem, I found a good solution for this one.
There is a private method System.Configuration.SettingsPropertyValue.IsHostedInAspnet
, which does exactly what I need. Being a private method, I do not want to call it (though I could using reflection), but its implementation is trivial:
private bool IsHostedInAspnet()
{
return (AppDomain.CurrentDomain.GetData(".appDomain") != null);
}
(according to Reflector)
Looks like there is a special key in the app domain data - ".appDomain", which is set when running in ASP.NET web server.
I will stick to that.
You can Find out the current process name:
Process p = Process.GetCurrentProcess();
string assemblyName = p.ProcessName;
and then check if this is the ASP.NET process name
The best option is a config setting.
It's better for testability; it's better because it's an obvious statement of how the code will work, and it's better because it doesn't rely on implementation details; you specifically branch from a value you set. It may be that the decision you are making is non-obvious and your variable/config can be suggestive of the reasoning.
It's the option I'd go for.
You can check for
HttpContext.Current
If it is not null then it is run from a web app.
See HttpContext.Current Property