您的位置:首页 > 其它

How to create a generic WCF service proxy ?

2013-10-10 05:31 357 查看
/*

Author: Jiangong SUN

*/

WCF Service Client:

/// <summary>
/// A WCF service client.
/// </summary>
/// <typeparam name="TContract">The type of the service contract.</typeparam>
internal class ServiceClient<TContract> : IDisposable
where TContract : class
{
/// <summary>
/// The service client object.
/// </summary>
private TContract client;

/// <summary>
/// Initializes a new instance of the ServiceClient class.
/// </summary>
/// <param name="endpointName">The name of the endpoint to use.</param>
public ServiceClient(string endpointName)
{
ChannelFactory<TContract> f = new ChannelFactory<TContract>(endpointName);
this.client = f.CreateChannel();
}

/// <summary>
/// Calls an operation on the service.
/// </summary>
/// <typeparam name="TResult">The type of the object returned by the service operation.</typeparam>
/// <param name="operation">The operation to call.</param>
/// <returns>The results of the service operation.</returns>
public TResult ServiceOperation<TResult>(Func<TContract, TResult> operation)
{
return operation(this.client);
}

/// <summary>
/// Calls an operation on the service.
/// </summary>
/// <param name="operation">The operation to call.</param>
public void ServiceOperation(Action<TContract> operation)
{
operation(this.client);
}

/// <summary>
/// Disposes this object.
/// </summary>
public void Dispose()
{
try
{
if (this.client != null)
{
IClientChannel channel = this.client as IClientChannel;
if (channel.State == CommunicationState.Faulted)
{
channel.Abort();
}
else
{
channel.Close();
}
}
}
finally
{
this.client = null;
GC.SuppressFinalize(this);
}
}
}


[ServiceContract]
public interface IHelloWorldService
{
[OperationContract]
string GetMessage(string name);

[OperationContract]
string GetPersonCompleteInfo(Person person);
}

[DataContract]
public class Person
{
[DataMember]
public int Age { get; set; }

[DataMember]
public string Sex { get; set; }

[DataMember]
public string Name { get; set; }
}
static void Main(string[] args)
{
WSHttpBinding basicHttpBinding = new WSHttpBinding();
EndpointAddress endpointAddress = new EndpointAddress("http://localhost:8080/HostDevServer/HelloWorldService.svc");
var service = new ChannelFactory<IHelloWorldService>(basicHttpBinding, endpointAddress).CreateChannel();
var message = service.GetMessage("hello world!");
Console.WriteLine(message);
}


reference:
http://huseyincakir.wordpress.com/2009/03/08/wcf-services-in-net-without-using-%E2%80%9Cadd-service-reference/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: