简体   繁体   中英

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. 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. The problem is that Widgets returned by the service are ServiceReference1.Widget but the client program expects 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.

I'm also guessing you are autogenerating the client based on the service layer. Don't do this for the shared DLL scenario. See this article:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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