How to determine if .NET code is running in an ASP.NET process?

后端 未结 6 1717
一生所求
一生所求 2020-12-17 15:19

I have an instance of a general purpose class that will be executed both under ASP.NET and a stand alone program. This code is sensative to the process where it is being run

6条回答
  •  爱一瞬间的悲伤
    2020-12-17 15:24

    I think what you really want to do is rethink your design. A better way to do this is to use a Factory class that produces different versions of the classes you need (designed to implement interfaces so you can use them interchangeably) depending on how the application is started. This will localize the code to detect web- and non-web-based usage in one place rather than scattering it all over your code.

    public interface IDoFunctions
    {
        void DoSomething();
    }
    
    public static class FunctionFactory
    {
      public static IDoFunctions GetFunctionInterface()
      {
         if (HttpContext.Current != null)
         {
            return new WebFunctionInterface();
         }
         else
         {
            return new NonWebFunctionInterface();
         }
       }
    }
    
    public IDoFunctions WebFunctionInterface
    {
        public void DoSomething()
        {
            ... do something the web way ...
        }
    }
    
    public IDoFunctions NonWebFunctionInterface
    {
        public void DoSomething()
        {
            ... do something the non-web way ...
        }
    }
    

提交回复
热议问题