Transparent proxy class of WCF, dynamic call, support for async/await, wcfasync

Source: Internet
Author: User

Transparent proxy class of WCF, dynamic call, support for async/await, wcfasync

We hope that the call by the WCF client will adopt the transparent proxy method, without adding service references or using the Invoke method, and use the ChannelFactory <> dynamic generation channel to call the service interface, and supports async/await. Of course, you do not need to configure serviceModel in Config.

Server code:

[ServiceContract]public interface IGameService{    [OperationContract]    Task DoWorkAsync(string arg);    [OperationContract]    void DoWork(string arg);}public class GameService : IGameService{    public async Task<string> DoWorkAsync(string arg)    {        return await Task.FromResult($"Hello {arg}, I am the GameService.");    }    public string DoWork(string arg)    {        return $"Hello {arg}, I am the GameService.";    }}[ServiceContract]public interface IPlayerService{    [OperationContract]    Task<string> DoWorkAsync(string arg);    [OperationContract]    string DoWork(string arg);}public class PlayerService : IPlayerService{    public async Task<string> DoWorkAsync(string arg)    {        return await Task.FromResult($"Hello {arg}, I am the PlayerService.");    }    public async string DoWork(string arg)    {        return $"Hello {arg}, I am the PlayerService.";    }}

 

Proxy

Dynamically create service objects, use ChannelFactory <T>, an abstract class

namespace Wettery.Infrastructure.Wcf{    public enum WcfBindingType    {        BasicHttpBinding,        NetNamedPipeBinding,        NetPeerTcpBinding,        NetTcpBinding,        WebHttpBinding,        WSDualHttpBinding,        WSFederationHttpBinding,        WSHttpBinding    }    public abstract class WcfChannelClient<TChannel> : IDisposable    {        public abstract string ServiceUrl { get; }        private Binding _binding;        public virtual Binding Binding        {            get            {                if (_binding == null)                    _binding = CreateBinding(WcfBindingType.NetTcpBinding);                return _binding;            }        }        protected TChannel _channel;        public TChannel Channel        {            get { return _channel; }        }        protected IClientChannel ClientChannel        {            get { return (IClientChannel)_channel; }        }        public WcfChannelClient()        {            if (string.IsNullOrEmpty(this.ServiceUrl)) throw new NotSupportedException("ServiceUrl is not overridden by derived classes.");            var chanFactory = new ChannelFactory<TChannel>(this.Binding, this.ServiceUrl);            _channel = chanFactory.CreateChannel();            this.ClientChannel.Open();        }        protected virtual void Dispose(bool disposing)        {            if (disposing && this.ClientChannel != null)            {                try                {                    this.ClientChannel.Close(TimeSpan.FromSeconds(2));                }                catch                {                    this.ClientChannel.Abort();                }            }            //TODO: free unmanaged resources        }        public void Dispose()        {            Dispose(true);            GC.SuppressFinalize(this);        }        ~WcfChannelClient()        {            Dispose(false);        }        private static Binding CreateBinding(WcfBindingType binding)        {            Binding bindinginstance = null;            if (binding == WcfBindingType.BasicHttpBinding)            {                BasicHttpBinding ws = new BasicHttpBinding();                ws.MaxBufferSize = 2147483647;                ws.MaxBufferPoolSize = 2147483647;                ws.MaxReceivedMessageSize = 2147483647;                ws.ReaderQuotas.MaxStringContentLength = 2147483647;                ws.CloseTimeout = new TimeSpan(0, 10, 0);                ws.OpenTimeout = new TimeSpan(0, 10, 0);                ws.ReceiveTimeout = new TimeSpan(0, 10, 0);                ws.SendTimeout = new TimeSpan(0, 10, 0);                bindinginstance = ws;            }            else if (binding == WcfBindingType.NetNamedPipeBinding)            {                NetNamedPipeBinding ws = new NetNamedPipeBinding();                ws.MaxReceivedMessageSize = 65535000;                bindinginstance = ws;            }            else if (binding == WcfBindingType.NetPeerTcpBinding)            {                //NetPeerTcpBinding ws = new NetPeerTcpBinding();                //ws.MaxReceivedMessageSize = 65535000;                //bindinginstance = ws;                throw new NotImplementedException();            }            else if (binding == WcfBindingType.NetTcpBinding)            {                NetTcpBinding ws = new NetTcpBinding();                ws.MaxReceivedMessageSize = 65535000;                ws.Security.Mode = SecurityMode.None;                bindinginstance = ws;            }            else if (binding == WcfBindingType.WebHttpBinding)            {                WebHttpBinding ws = new WebHttpBinding(); //Restful style                ws.MaxReceivedMessageSize = 65535000;                bindinginstance = ws;            }            else if (binding == WcfBindingType.WSDualHttpBinding)            {                WSDualHttpBinding ws = new WSDualHttpBinding();                ws.MaxReceivedMessageSize = 65535000;                bindinginstance = ws;            }            else if (binding == WcfBindingType.WSFederationHttpBinding)            {                WSFederationHttpBinding ws = new WSFederationHttpBinding();                ws.MaxReceivedMessageSize = 65535000;                bindinginstance = ws;            }            else if (binding == WcfBindingType.WSHttpBinding)            {                WSHttpBinding ws = new WSHttpBinding(SecurityMode.None);                ws.MaxReceivedMessageSize = 65535000;                ws.Security.Message.ClientCredentialType = MessageCredentialType.Windows;                ws.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;                bindinginstance = ws;            }            return bindinginstance;        }            }}
View Code

A proxy class is derived for each WCF Service. In this class, ServiceUrl and Binding can be rewritten. ServiceUrl can be configured in Config. By default, NetTcpBinding is used when Binding is not rewritten.

public class GameServiceClient : WcfChannelClient<IGameService>    {        public override string ServiceUrl        {            get            {                return "net.tcp://localhost:21336/GameService.svc";            }        }    }public class PlayerServiceClient : WcfChannelClient<IPlayerService>    {        public override string ServiceUrl        {            get            {                return "net.tcp://localhost:21336/PlayerService.svc";            }        }    }

Client call

Using (var client = new GameServiceClient () {client. channel. doWork ("thinkpig"); // No return value await client. channel. doWorkAsync ("thinkpig"); // asynchronous} using (var client = new PlayerServiceClient () {var result = client. channel. doWork ("thinkdog"); // return value result = await client. channel. doWorkAsync ("thinkdog"); // asynchronous with returned values}

 

For more information about the WCF host, see the first two articles.

WCF binds netTcpBinding to host the console application

WCF binds netTcpBinding to host on IIS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.