Alex Rivera | Logout

How can C# Library Code know it's hosting application type without System.Web.dll?

Asked 2011-03-01T12:05:56.477
9

We are developing several applications in Visual Studio 2010 using C# and .NET 4.0 on Windows. Two SilverLight applications using services from several WCF projects. Another is a console application.

We want to put some "common" functionality in a separated Library project in order to factorize and reuse code. This library needs to know if the application is hosted (IIS, ASP.NET...) like the WCF services or is running as a console application, due to different file path handling.

Googling this question, people indicates the use of System.Web.dll in order to know if the code is hosted, using HttpContext, HostingEnvironment.IsHosted... The problem is that such approach requires to include a reference to System.Web int he Library project, being not acceptable if this Library will be referenced by a Console project with Client Profile.

The idea is to use another technique that do not involve the use of System.Web assembly.

Edit
Report

1 Answer

4

Another reflection idea: use System.Web, but through reflection:

  1. use AppDomain.CurrentDomain.GetAssemblies() to see if System.Web is loaded; if not, you're not hosted
  2. if it is loaded, use reflection to call HostingEnvironment.IsHosted

Turns out that's easier said than done, but this seems to do the trick:

public static bool IsHosted()
{
  try
  {
    var webAssemblies = AppDomain.CurrentDomain.GetAssemblies()
      .Where(a => a.FullName.StartsWith("System.Web"));
    foreach(var webAssembly in webAssemblies)
    {
      var hostingEnvironmentType = webAssembly.GetType("System.Web.Hosting.HostingEnvironment");
      if (hostingEnvironmentType != null)
      {
        var isHostedProperty = hostingEnvironmentType.GetProperty("IsHosted",
          BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.Public);
        if (isHostedProperty != null)
        {
          object result = isHostedProperty.GetValue(null, null);
          if (result is bool)
          {
            return (bool) result;
          }
        }
      }
    }
  }
  catch (Exception)
  {
    // Failed to find or execute HostingEnvironment.IsHosted; assume false
  }
  return false;
}

The reflection is probably expensive so execute once and cache the result. I'm also not sure what the best way to find the specific assembly and type is, but this way works.

answered 2011-03-01T12:44:49.313

Your Answer