开发者

WCF and [DATACONTRACT]+[DATAMEMBER]

开发者 https://www.devze.com 2023-03-08 05:30 出处:网络
I was wondering how to add the DataContract to my service? I mean, I know I have to create a class, put [DATACONTRACT] on top of it and then add [DATAMEMBER] on top of each members, but then how to ad

I was wondering how to add the DataContract to my service? I mean, I know I have to create a class, put [DATACONTRACT] on top of it and then add [DATAMEMBER] on top of each members, but then how to add the DataContract to the service (I already have a [ServiceContract] and [OperationContract] running on a service)??

I am doing everything programmaticaly at the moment (no .config file).

some piece of code showing how I launch and add my OperationContract: (I'm using .NET 4.0)

Service side:

            using开发者_JS百科 (ServiceHost host = new ServiceHost(typeof(StringReverser), new Uri[]{ new Uri("net.tcp://localhost") }))
            {

                   host.AddServiceEndpoint(typeof(IStringReverser), new NetTcpBinding(), "TCPReverse");

                   host.Open();
            }

Client side:

        Callbacks myCallbacks = new Callbacks();

        DuplexChannelFactory<IStringReverser> TCPFactory =
           new DuplexChannelFactory<IStringReverser>(
              myCallbacks,
              new NetTcpBinding());

        TCPFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password");
        IStringReverser TCPProxy = TCPFactory.CreateChannel();

        Console.WriteLine("Client connected");

Thanks in advance


You don't need to "add" data contract anywhere. You just have to use it as parameter or return value of any operation in your service contract or callback contract. Data contract defines data transferred as part of service request or response. If the data contract is not used by any operation of the service it has obviously no relation to the service (in case of metadata it is not included).

The only exception are some advanced scenarios with known types but that will probably not be the case in this question.


DataContracts are what are passed to the operations of your service. Generally if you have complex types as parameters you will decorate them with a DataContract attribute.

If your only dealing with primitive types as parameters there is nothing to decorate with DataContract.

0

精彩评论

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