2009-10-07 69 views
2

我有一个为所有DataAccess使用WCF的应用程序。它返回一些业务对象,它有一些操作。我应该在哪里将Comparers放入使用WCF的应用程序中?

此代码是否应存在于我的客户端或我的服务中?如果在服务中,我应该如何实现它?我可以简单地将它添加为我的业务对象的接口吗?这是通过WCF服务代理代码实现的吗?

(这是从MSDN的样本,我想在我实现我自己能得到一些反馈,但是这将是99%相同)

// Custom comparer for the Product class. 
class ProductComparer : IEqualityComparer<Product> 
{ 
    // Products are equal if their names and product numbers are equal. 
    public bool Equals(Product x, Product y) 
    { 

     // Check whether the compared objects reference the same data. 
     if (Object.ReferenceEquals(x, y)) return true; 

     // Check whether any of the compared objects is null. 
     if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) 
      return false; 

     // Check whether the products' properties are equal. 
     return x.Code == y.Code && x.Name == y.Name; 
    } 

    // If Equals() returns true for a pair of objects, 
    // GetHashCode must return the same value for these objects. 

    public int GetHashCode(Product product) 
    { 
     // Check whether the object is null. 
     if (Object.ReferenceEquals(product, null)) return 0; 

     // Get the hash code for the Name field if it is not null. 
     int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode(); 

     // Get the hash code for the Code field. 
     int hashProductCode = product.Code.GetHashCode(); 

     // Calculate the hash code for the product. 
     return hashProductName^hashProductCode; 
    } 
} 

回答

2

请记住,在WCF传输的数据(或通过任何种类的基于SOAP的服务)仅为消息。它们没有任何行为(它不会互操作),所以你所有的好行为都将在翻译中失去。

这意味着你只有一个选择:你的业务逻辑必须驻留在服务中,因为它不能驻留在客户端。

也就是说,有几种方法可以在服务和客户端之间共享代码,但除非您纯粹将WCF用作通信堆栈,否则不建议这样做,因为它会将客户端和服务绑定在一起,并使其几乎不可能独立地改变这两者(更不用说让新客户使用该服务)。

+0

优秀 - 说得好! – 2009-10-07 19:31:38

+0

多数民众赞成我以为 - 所以我需要做一个方法,暴露这个比较从我的WCF服务公开? – Nate 2009-10-07 19:58:41

+0

我的目标是能够在客户端做到这一点,做我自己的比较:productsA.Except(productsB)(其中两个都是IEnumerable)。 – Nate 2009-10-07 20:00:13

3

那么,WCF生成的代理是partial类,所以即使您使用的是mex代,您也可以在客户端添加行为。你也可以使用程序集共享(/reference在命令行,或选中IDE中的方框) - 然后你可以在客户端和服务器上使用完全相同的类型,但是它破坏了大多数“纯”的规则, SOA。

这取决于你觉得多“纯”,我想。纯粹的,但不得不维护两个类似的代码库的痛苦可能超过了方便但是大会共享的肮脏。这取决于应用程序是什么。我很高兴在很多场合都使用过汇编,我觉得没有罪恶感;这是该场景最明智的选择。

只要记住,客户端代码是方便 - 始终把客户作为敌对的,所以即使你客户使用装配共享,请记住,一个敌对的客户可能没有,所以不会坚持你的规则;始终在服务器上进行验证。

+0

我认为最好在客户端执行此操作,因为此比较的最终结果仅用于显示目的。 – Nate 2009-10-07 20:51:29

相关问题