tofutim
tofutim

Reputation: 23394

How can I generate WCF .cs file for both Silverlight and .NET?

I currently use the Silverlight version of svcutil to generate the .cs file for Silverlight. I would like to be able to share this with .NET 3.5, but there seem to be some obstacles. Notably, ChannelBase does not seem to exist in .NET, and neither does IHttpCookieContainerManager. Is it possible to doctor my Service.cs so that it is readable by both? (I prefer not to use a .config file.)

Upvotes: 2

Views: 709

Answers (1)

Phil
Phil

Reputation: 6679

If you don't use svcutil, you can do this easily. If your service interface is shared by Silverlight and .Net 3.5, just use some simple code to create a client at runtime.

Note: You will need to create two slightly different interfaces, since Silverlight ONLY supports asynchronous communication. Or you can use the same interface and use #if SILVERLIGHT to tell the compiler to only compile one part of file when compiling Silverlight code, and another part of the file when compiling .NET code. An example:

[ServiceContract(Namespace="http://www.example.com/main/2010/12/21")]
public interface IService
{
#if SILVERLIGHT
        [OperationContract(AsyncPattern=true, Action = "http://www.example.com/HelloWorld", ReplyAction = "http://www.example.com/HelloWorldReply")]
        IAsyncResult BeginHelloWorld(AsyncCallback callback, object state);
        string EndHelloWorld(IAsyncResult result);
#else
        [OperationContract(Action="http://www.example.com/HelloWorld", ReplyAction="http://www.example.com/HelloWorldReply")]
        string HelloWorld();
#endif
}

This allows you to call myClient.BeginHelloWorld() and myClient.EndHelloWorld() when using Silverlight, or just myClient.HelloWorld() when using .Net 3.5.

If you have a lot of custom binding going on, you can also create a class that inherits from CustomBinding and have that class be shared between .Net and Silverlight as well. An example of such a class:

public class MyServiceBinding : CustomBinding
{
    public MyServiceBinding()
    {
        BinaryMessageEncodingBindingElement binaryEncodingElement = new BinaryMessageEncodingBindingElement();

#if !SILVERLIGHT
        binaryEncodingElement.ReaderQuotas.MaxArrayLength = int.MaxValue;
#endif

        Elements.Add(binaryEncodingElement);
        Elements.Add(new HttpTransportBindingElement() { MaxReceivedMessageSize = int.MaxValue });
    }
}

Upvotes: 1

Related Questions