2011-10-12 60 views
2

我有一个WCF服务契约实现,可以用作一个普通的dll或作为一个Web服务。有没有什么方法可以从代码中识别它是如何使用的。 更具体地说,我需要在这些情况下抛出不同的例外。如何识别代码是否在web服务中运行?

谢谢

+0

需要一些更多的信息。您是否有示例代码,如果这是一个封闭的源代码组件,您是否有示例客户端代码? – MatthewMartin

+0

您可以使用OperationContext类来找出调用WCF服务的机器的IP地址,并查看它是否是您的Web服务器的地址? – GrandMasterFlush

+0

好吧,它很简单。我有一个公共类Service:IService {},其中IService被定义为ServiceContract。服务可以通过Web服务中的端点公开,也可以通过引用应用程序中的dll访问。 – user991759

回答

0

很公平。在这种情况下,您可以检查库中的各种上下文。

WCF

bool isWcf = OperationContext.Current != null; 

网络

bool isWeb = System.Web.HttpContext.Current != null; 
+0

这可能是答案,我会在试用后回来。 – user991759

1

我不确定自己的具体要求,但似乎平原DLL是一个标准的业务逻辑库。根据我的经验,我建议尽可能地将业务逻辑作为实现不可知的方式(理所当然),因为无论如何您都可能会以不同的方式处理异常。通过基于实现抛出不同的异常,您将把业务逻辑的责任与实现者的责任混合在一起。

我的建议是从业务逻辑库中抛出一组常见的异常,并针对每个实现对它们进行不同的处理/处理。例如。一个控制台应用程序可能会再次要求输入,因为WCF应用程序可能会抛出一个错误异常。

以下面的代码为例:

// Simple business logic that throws common exceptions 
namespace BusinessLogicLibrary 
{ 
    public class Math 
    { 
     public static int Divide(int dividend, int divisor) 
     { 
      if (divisor == 0) 
       throw new DivideByZeroException(); 

      return dividend/divisor; 
     } 
    } 
} 

// WCF calls to business logic and handles the exception differently 
namespace WcfProject 
{ 
    [ServiceContract] 
    public interface IService 
    { 
     [OperationContract] 
     int Divide(int dividend, int divisor); 
    } 

    public class Service : IService 
    { 
     public int Divide(int dividend, int divisor) 
     { 
      try 
      { 
       return BusinessLogicLibrary.Math.Divide(dividend, divisor); 
      } 
      catch (Exception ex) 
      { 
       throw new FaultException(
        new FaultReason(ex.Message), 
        new FaultCode("Division Error")); 
      } 
     } 
    } 
} 

// Console application calls library directly and handles the exception differently 
namespace ConsoleApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      ShowDivide(); 
     } 

     static void ShowDivide() 
     { 
      try 
      { 
       Console.WriteLine("Enter the dividend: "); 
       int dividend = int.Parse(Console.ReadLine()); 

       Console.WriteLine("Enter the divisor: "); 
       int divisor = int.Parse(Console.ReadLine()); 

       int result = BusinessLogicLibrary.Math.Divide(dividend, divisor); 
       Console.WriteLine("Result: {0}", result); 
      } 
      catch (DivideByZeroException) 
      { 
       // error occurred but we can ask the user again 
       Console.WriteLine("Cannot divide by zero. Please retry."); 
       ShowDivide(); 
      } 
     } 
    } 
} 
+0

承载是的,这是一种常见的方法,但不幸的是在这种情况下不是一种选择。 – user991759

相关问题