开发者

WCF Service and Interface - the result is object, even though ServiceKnownType was used

I need to convert some objects that are not compatible with Silverlight to models to send over a WCF service. I've tried using the ServiceKnownType, but the result is still object. I am able to cast the object to the Model after I retreive the result, but I don't want to have to do that every time. Here is an example of what I have attempted.

Is this a good approach? Why doesn't WCF ret开发者_开发百科urn a BikeModel as an object.

Interface

public interface IBike
{
  string BikeName { get; set;}
}

Model

[DataContract]
public class BikeModel : IBike
{
  [DataMember]
  public string BikeName { get; set; }
}

Other Object that can't be used in Silverlight because of MarshalObjectByRef etc in base class

public class Bike : IBike, UnusableBaseClass
{
....
}

IService1

[ServiceContract]
[ServiceKnownType(typeof(BikeModel))]
public interface IService1
{
    [OperationContract]
    IBike GetBike();
}

Service

 public class Service1 : IService1
 {
   public IBike GetBike()
   {
     Bike b = BikeManager.GetFirstBikeInTheDataBase();
     return b;
    }
 }

MainPage.xaml.cs -

public MainPage()
{
  InitializeComponent();
  this.Loaded += (s, a) =>
  {
     ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
     client.GetBikeCompleted += (sender, e) =>
     {
        var d = e.Result;
        // this cast works
        BikeModel model = (BikeModel)d;
      };
      client.GetBikeAsync();

    };
}


Is this just a typo, or is that really like this in your model?? The model class should be decorated with [DataContract] - not [DataMember]. It should be like this:

[DataContract]
public class BikeModel : IBike
{
  [DataMember]
  public string BikeName { get; set; }
}

UPDATE: okay, that was just a typo.

Can you try this? Turn your IBike interface into a BaseBike base class:

public class BaseBike
{
  string BikeName { get; set;}
}

and then return that base type from your call

[ServiceContract]
[ServiceKnownType(typeof(BikeModel))]
public interface IService1
{
    [OperationContract]
    BaseBike GetBike();
}

Does that change anything at all? I know WCF is a bit picky about what can be serialized around - since all that's serialized must be representable in XML schema, you cannot easily use interfaces and/or generics.

The other option you could try is to use the more focused [KnownType] attribute on the operation, instead of the [ServiceKnownType]. Again - not sure if it'll help, I'm fishing for ideas here.... (your stuff looks OK from a .NET standpoint - but WCF communication isn't always quite the same world....)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜