简体   繁体   English

在客户端程序中使用WCF服务中的对象

[英]Using object from WCF Service in my client program

I sure I'm missing something simple and obvious here but I can't find the answer: I have a WCF service that returns Widgets. 我确定我在这里缺少简单明了的东西,但找不到答案:我有一个返回Widget的WCF服务。 Widgets are defined in the service. 小部件在服务中定义。 In my client program I also define and use Widgets. 在我的客户程序中,我还定义和使用小部件。 The Widget definition in the client and the service are identical. 客户端和服务中的Widget定义相同。 The problem is that Widgets returned by the service are ServiceReference1.Widget but the client program expects MyProgram.Widget. 问题是服务返回的小部件是ServiceReference1.Widget,但是客户端程序需要MyProgram.Widget。 How do I get the client program to work with the service Widgets? 如何使客户端程序与服务小部件一起使用?

On the service: 关于服务:

[DataContract]
public class Widget
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public decimal Price { get; set; }
}

public class Service1
{
    public async Task<IEnumerable<Widget>> GetAllWidgets()
    {
        await Task.Delay(Util.GetDelay(), CancellationToken.None);
        return GetAllWidgets();
    }   
}

In the client program I also define Widgets. 在客户端程序中,我还定义了小部件。 I call the service to get some: 我打电话给服务获得一些:

    public async Task<List<Widget>> GetWidgetsAsync() // expects MyProgram.Widget
    {
        using (ServiceReference1.Service1Client client = 
                 new ServiceReference1.Service1Client()) 
        {
            var response = await client.GetAllProductsAsync();
            return response;  // gets ServiceReference1.Widget
        }
    }

Do I need to iterate through the response and build a duplicate set of client Widgets? 我是否需要遍历响应并构建重复的客户端小部件集? Or do I define Widgets in a separate library and reference it from both client and server? 还是我在单独的库中定义小部件并从客户端和服务器两者中引用它?

Thanks 谢谢

The best way is to put the passed type (DTOs) and Service Interfaces into a shared library and reference it in both projects. 最好的方法是将传递的类型(DTO)和服务接口放入共享库中,并在两个项目中对其进行引用。

I'm also guessing you are autogenerating the client based on the service layer. 我还猜测您正在基于服务层自动生成客户端。 Don't do this for the shared DLL scenario. 不要为共享DLL方案执行此操作。 See this article: 看到这篇文章:

http://blog.walteralmeida.com/2010/08/wcf-tips-and-tricks-share-types-between-server-and-client.html http://blog.walteralmeida.com/2010/08/wcf-tips-and-tricks-share-types-between-server-and-client.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM