I am trying to update a library of shared code from .NET Framework to .NET Standard. The library has important dependencies on System.Web.Hosting.HostingEnvironment.IsHosted
and HostingEnvironment.ApplicationID
.
The library is precompiled into an assembly, and assembly is referenced across many projects:
- .NET Framework console apps
- .NET Framework Windows Forms apps
- .NET Framework Windows services
- Standalone ASP.NET website (bespoke code for a client, often as a web service)
- Extension to ASP.NET site written by third-party. (Create new ascx controls with compiled code-behind added to \bin\ folder)
(Precompile is so that updated versions of the assembly can be dropped in place on solutions that already reference it.)
The library provides mostly code accelerators -- standardized database access, logging, license checking, type conversions, etc. The logging features are not only used by the calling project, but are also called by other parts of the library. For example, license checking relies on database access, and database errors are written to the log.
The logging area is a sticking point, especially in the context of bullet 5. The parent application may be served up from multiple IIS websites in multiple app pools. Or multiple IIS sites using the same app pool. Or from different subfolders on the same site, but in different app pools. When the library detects it is being run from inside IIS, logs are written to different files based on appId and application pool name. (E.G. MyCompany.2.PublicSitePool.log
inside IIS, or just MyCompany.log
when not in IIS)
On .NET Framework, I use System.Web.Hosting.HostingEnvironment.IsHosted
to detect when I'm running in IIS, obtain the appId using HostingEnvironment.ApplicationID
, and the app pool name comes from System.Environment.UserName
.
I am trying to retarget the project for .NET Standard, so the library can be used equally well with .NET Core projects. System.Web.Hosting
is not available on .NET Core. I'm looking for a solution that can either:
- Give me consistent results on both .NET Framework and .NET Core or
- Explicitly detect whether running in .NET Framework or .NET Core, and then use appropriate techniques for the platform
I already have the "am I in IIS" check running as a singleton in the class constructor. Reflection does not thrill me but is a reasonable option if needed.
I have already reviewed these questions (and a few others). Some useful ideas, but no single solution. Reading settings from *.config is not an option. Asking the calling application to specify "hosted" or "not hosted" is the least attractive option that I know will work, because it will break all existing solutions that use this code.
HostingEnvironment does not contain a definition for IsHosted
How determine if an application is a web application in .NET Core?
How to tell if code is running on web server without using System.Web?