代码之家  ›  专栏  ›  技术社区  ›  Nate CSS Guy

在使用WCF的应用程序中,我应该将比较器放在哪里?[关闭]

  •  2
  • Nate CSS Guy  · 技术社区  · 15 年前

    我有一个应用程序使用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 回复  |  直到 15 年前
        1
  •  2
  •   Mark Seemann    15 年前

    记住,通过WCF(或通过任何基于SOAP的服务)传输的数据是 信息 只有。它们不携带任何行为(它不具有互操作性),所以您所有的好行为都将在翻译中丢失。

    这意味着您实际上只有一个选项:您的业务逻辑必须驻留在服务中,因为它不能驻留在客户机上。

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

        2
  •  3
  •   Marc Gravell    15 年前

    嗯,wcf生成的代理是 partial 类,这样您就可以在客户机上添加行为,即使您使用的是MEX生成。

    也可以使用程序集共享( /reference 在命令行中,或者选中IDE中的复选框),然后您可以在客户机和服务器上使用完全相同的类型,但它打破了大多数“纯”SOA的规则。

    我想,这取决于你感觉“纯洁”的程度。纯粹但必须维护两个相似的代码基的痛苦可能会超过程序集共享的便利性和可怕性。这取决于应用程序是什么。我已经在很多场合愉快地使用了组装共享,并且我没有感到内疚;这是场景中最明智的选择。

    记住,客户机代码是 方便 -始终将客户视为敌意,因此即使 你的 客户机使用程序集共享,请记住,敌对客户机可能不会,因此不会遵守您的规则;始终在服务器上验证。