namespace wcfflow
{
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Dispatcher;
    using System.Reflection;
    using System.ServiceModel.Channels;
    using System.Threading;
    using System.Globalization;
    using System.Text;
    using System.ServiceModel.Description;
    using System.Linq;
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
    public class CommentAttribute : Attribute
    {
        public string Message { get; set; }
        public CommentAttribute(string message)
        {
            this.Message = message;
        }
    }
class MyDispatchMessageInspector : IDispatchMessageInspector
    {
        public MyDispatchMessageInspector()
        {
        }
        [Comment("在已接收入站消息后将消息调度到应发送到的操作之前调用")]
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return null;
        }
        [Comment("在操作已返回后发送回复消息之前调用")]
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
        }
    }
    class MyDispatchMessageFormatter : IDispatchMessageFormatter
    {
        IDispatchMessageFormatter inner;
        public MyDispatchMessageFormatter(IDispatchMessageFormatter inner)
        {
            this.inner = inner;
        }
        [Comment("将消息反序列化为参数数组")]
        public void DeserializeRequest(Message message, object[] parameters)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            this.inner.DeserializeRequest(message, parameters);
        }
        [Comment("从指定的消息版本、参数数组和返回值序列化答复消息")]
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return this.inner.SerializeReply(messageVersion, parameters, result);
        }
    }
    class MyClientMessageInspector : IClientMessageInspector
    {
        public MyClientMessageInspector()
        {
        }
        [Comment("在收到回复消息之后将它传递回客户端应用程序之前,启用消息的检查或修改")]
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Yellow, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
        }
        [Comment("在将请求消息发送到服务之前,启用消息的检查或修改")]
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Yellow, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return null;
        }
    }
    class MyClientMessageFormatter : IClientMessageFormatter
    {
        IClientMessageFormatter inner;
        public MyClientMessageFormatter(IClientMessageFormatter inner)
        {
            this.inner = inner;
        }
        [Comment("将消息转换为将传回给调用操作的返回值和 out 参数")]
        public object DeserializeReply(Message message, object[] parameters)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Yellow, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return this.inner.DeserializeReply(message, parameters);
        }
        [Comment("将 Object 数组转换为出站 Message")]
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Yellow, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return this.inner.SerializeRequest(messageVersion, parameters);
        }
    }
    class MyDispatchOperationSelector : IDispatchOperationSelector
    {
        [Comment("将本地操作与传入的方法相关联")]
        public string SelectOperation(ref Message message)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            string action = message.Headers.Action;
            );
            return method;
        }
    }
    class MyParameterInspector : IParameterInspector
    {
        ConsoleColor consoleColor;
        bool isServer;
        public MyParameterInspector(bool isServer)
        {
            this.isServer = isServer;
            this.consoleColor = isServer ? ConsoleColor.Cyan : ConsoleColor.Yellow;
        }
        [Comment("在客户端调用返回之后、服务响应发送之前调用")]
        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), this.consoleColor, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
        }
        [Comment("在发送客户端调用之前、服务响应返回之后调用")]
        public object BeforeCall(string operationName, object[] inputs)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), this.consoleColor, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return null;
        }
    }
    class MyCallContextInitializer : ICallContextInitializer
    {
        [Comment("实现它来参与清理调用该操作的线程")]
        public void AfterInvoke(object correlationState)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
        }
        [Comment("实现它来参与初始化操作线程")]
        public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return null;
        }
    }
    class MyOperationInvoker : IOperationInvoker
    {
        IOperationInvoker inner;
        public MyOperationInvoker(IOperationInvoker inner)
        {
            this.inner = inner;
        }
        [Comment("返回参数对象的 System.Array")]
        public object[] AllocateInputs()
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return this.inner.AllocateInputs();
        }
        [Comment("从一个实例和输入对象的集合返回一个对象和输出对象的集合")]
        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return this.inner.Invoke(instance, inputs, out outputs);
        }
        [Comment("开始异步方法")]
        public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return this.inner.InvokeBegin(instance, inputs, callback, state);
        }
[Comment("结束异步方法")]
        public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return this.inner.InvokeEnd(instance, out outputs, result);
        }
public bool IsSynchronous
        {
            [Comment("获取一个值,该值指定调度程序是调用 Invoke 方法还是调用 InvokeBegin 方法")]
            get
            {
                ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
                return this.inner.IsSynchronous;
            }
        }
    }
    class MyInstanceProvider : IInstanceProvider
    {
        Type serviceType;
        public MyInstanceProvider(Type serviceType)
        {
            this.serviceType = serviceType;
        }
        [Comment("如果给出指定的 InstanceContext 对象,则返回服务对象")]
        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return Activator.CreateInstance(this.serviceType);
        }
        [Comment("如果给出指定的 InstanceContext 对象,则返回服务对象")]
        public object GetInstance(InstanceContext instanceContext)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return Activator.CreateInstance(this.serviceType);
        }
        [Comment("在 InstanceContext 对象回收服务对象时调用")]
        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
        }
    }
    class MyInstanceContextProvider : IInstanceContextProvider
    {
        IInstanceContextProvider inner;
        public MyInstanceContextProvider(IInstanceContextProvider inner)
        {
            this.inner = inner;
        }
        [Comment("接收新消息时调用")]
        public InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return this.inner.GetExistingInstanceContext(message, channel);
        }
        [Comment("当从 GetExistingInstanceContext 方法返回 null 引用时调用")]
        public void InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            this.inner.InitializeInstanceContext(instanceContext, message, channel);
        }
        [Comment("当 InstanceContext 活动完成时调用,以使实施者能阻止 InstanceContext 的回收")]
        public bool IsIdle(InstanceContext instanceContext)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return this.inner.IsIdle(instanceContext);
        }
        [Comment("当 IsIdle 方法返回 false 时调用,以使实施者能提供回调,从而通知 InstanceContext 对象的完成时间")]
        public void NotifyIdle(InstanceContextIdleCallback callback, InstanceContext instanceContext)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            this.inner.NotifyIdle(callback, instanceContext);
        }
    }
    class MyInstanceContextInitializer : IInstanceContextInitializer
    {
        [Comment("用于修改新创建的 InstanceContext 对象")]
        public void Initialize(InstanceContext instanceContext, Message message)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
        }
    }
    class MyChannelInitializer : IChannelInitializer
    {
        ConsoleColor consoleColor;
        public MyChannelInitializer(bool isServer)
        {
            this.consoleColor = isServer ? ConsoleColor.Cyan : ConsoleColor.Yellow;
        }
        [Comment("使用指定的 IClientChannel 来初始化 IChannelInitializer 类")]
        public void Initialize(IClientChannel channel)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), this.consoleColor, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
        }
    }
    class MyClientOperationSelector : IClientOperationSelector
    {
        public bool AreParametersRequiredForSelection
        {
            [Comment("获取一个值,指示是否需要参数来确定选择")]
            get
            {
                ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Yellow, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
                return false;
            }
        }
        [Comment("返回选择的操作")]
        public string SelectOperation(MethodBase method, object[] parameters)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Yellow, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return method.Name;
        }
    }
    class MyInteractiveChannelInitializer : IInteractiveChannelInitializer
    {
        [Comment("要开始使用用户接口获取凭据信息的异步调用")]
        public IAsyncResult BeginDisplayInitializationUI(IClientChannel channel, AsyncCallback callback, object state)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Yellow, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            Action act = new Action(this.DoNothing);
            return act.BeginInvoke(callback, state);
        }
        [Comment("当 BeginDisplayInitializationUI 已完成时调用")]
        public void EndDisplayInitializationUI(IAsyncResult result)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Yellow, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
        }
        private void DoNothing() { }
    }
    class MyErrorHandler : IErrorHandler
    {
        [Comment("启用错误相关处理并返回一个值,该值指示调度程序在某些情况下是否中止会话和实例上下文")]
        public bool HandleError(Exception error)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            return error is ArgumentException;
        }
        [Comment("启用创建从服务方法过程中的异常返回的自定义 FaultException(TDetail)")]
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Cyan, "{0}.{1}", this.GetType().GetInterfaces().FirstOrDefault().FullName, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            MessageFault messageFault = MessageFault.CreateFault(new FaultCode("FaultCode"), new FaultReason(error.Message));
            fault = Message.CreateMessage(version, messageFault, "FaultAction");
        }
    }
    class MyBehavior : IOperationBehavior, IContractBehavior,IEndpointBehavior,IServiceBehavior
    {
        public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
        {
        }
        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
        {
            clientOperation.Formatter = new MyClientMessageFormatter(clientOperation.Formatter);
            clientOperation.ParameterInspectors.Add(new MyParameterInspector(false));
        }
        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
            dispatchOperation.CallContextInitializers.Add(new MyCallContextInitializer());
            dispatchOperation.Formatter = new MyDispatchMessageFormatter(dispatchOperation.Formatter);
            dispatchOperation.Invoker = new MyOperationInvoker(dispatchOperation.Invoker);
            dispatchOperation.ParameterInspectors.Add(new MyParameterInspector(true));
        }
        public void Validate(OperationDescription operationDescription)
        {
        }
        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }
        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.ChannelInitializers.Add(new MyChannelInitializer(false));
            clientRuntime.InteractiveChannelInitializers.Add(new MyInteractiveChannelInitializer());
            clientRuntime.MessageInspectors.Add(new MyClientMessageInspector());
            clientRuntime.OperationSelector = new MyClientOperationSelector();
        }
        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            dispatchRuntime.ChannelDispatcher.ChannelInitializers.Add(new MyChannelInitializer(true));
            dispatchRuntime.ChannelDispatcher.ErrorHandlers.Add(new MyErrorHandler());
            dispatchRuntime.InstanceContextInitializers.Add(new MyInstanceContextInitializer());
            dispatchRuntime.InstanceContextProvider = new MyInstanceContextProvider(dispatchRuntime.InstanceContextProvider);
            dispatchRuntime.InstanceProvider = new MyInstanceProvider(dispatchRuntime.ChannelDispatcher.Host.Description.ServiceType);
            dispatchRuntime.MessageInspectors.Add(new MyDispatchMessageInspector());
            dispatchRuntime.OperationSelector = new MyDispatchOperationSelector();
        }
        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
        }
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            throw new NotImplementedException();
        }
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            throw new NotImplementedException();
        }
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            throw new NotImplementedException();
        }
        public void Validate(ServiceEndpoint endpoint)
        {
            throw new NotImplementedException();
        }
        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
            throw new NotImplementedException();
        }
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            throw new NotImplementedException();
        }
        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            throw new NotImplementedException();
        }
    }
    static class ColorConsole
    {
        static object syncRoot = new object();
        public static void WriteLine(MethodBase method, ConsoleColor color, string text, params object[] args)
        {
            var message = method.GetCustomAttributes(typeof(CommentAttribute), true).OfType<CommentAttribute>().FirstOrDefault();
            )
            {
                text = string.Format(CultureInfo.InvariantCulture, text, args);
            }
            lock (syncRoot)
            {
                Console.ForegroundColor = color;
                if (message == null)
                    Console.WriteLine("[{0}] 执行方法: {1}", DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture), text);
                else
                    Console.WriteLine("[{0}] //{1} 方法定义: {2}", DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture),message.Message, text);
                Console.ResetColor();
            }
            Thread.Sleep();
        }
        public static void WriteLine(string text, params object[] args)
        {
            Console.WriteLine(text, args);
        }
        public static void WriteLine(object obj)
        {
            Console.WriteLine(obj);
        }
    }
    static class ReflectionUtil
    {
        public static string GetMethodSignature(MethodBase method)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(method.Name);
            sb.Append("(");
            ParameterInfo[] parameters = method.GetParameters();
            ; i < parameters.Length; i++)
            {
                ) sb.Append(", ");
                sb.Append(parameters[i].ParameterType.Name);
            }
            sb.Append(")");
            return sb.ToString();
        }
    }
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        int Add(int x, int y);
        [OperationContract(IsOneWay = true)]
        void Process(string text);
    }
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class Service : ITest
    {
        public int Add(int x, int y)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Green, "执行服务方法 '{0}'", MethodBase.GetCurrentMethod().Name);
            )
            {
                throw new ArgumentException("出现一个异常,这是异常消息");
            }
            else
            {
                return x + y;
            }
        }
        public void Process(string text)
        {
            ColorConsole.WriteLine(MethodBase.GetCurrentMethod(), ConsoleColor.Green, "执行服务方法 '{0}'", MethodBase.GetCurrentMethod().Name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            //配置一个服务主机
            using (ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)))
            {
                //为主机添加一个服务终结点
                ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
                //为服务终结点添加自定义服务行为
                endpoint.Contract.Behaviors.Add(new MyBehavior());
                foreach (OperationDescription operation in endpoint.Contract.Operations)
                {
                    operation.Behaviors.Add(new MyBehavior());
                }
                host.Open();
                ColorConsole.WriteLine("打开服务");
                using (ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress)))
                {
                    factory.Endpoint.Contract.Behaviors.Add(new MyBehavior());
                    foreach (OperationDescription operation in factory.Endpoint.Contract.Operations)
                    {
                        operation.Behaviors.Add(new MyBehavior());
                    }
                    ITest proxy = factory.CreateChannel();
                    ColorConsole.WriteLine("即将调用服务");
                 //   ColorConsole.WriteLine(proxy.Add(3, 4));
                  //  ColorConsole.WriteLine("服务调用完成,再次调用服务,这次服务执行过程中会产生异常");
                    try
                    {
                        ColorConsole.WriteLine(proxy.Add());
                    }
                    catch (Exception e)
                    {
                        ColorConsole.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
                    }
                    //ColorConsole.WriteLine("现在开始调用单向的服务");
                    //proxy.Process("hello");
                    ((IClientChannel)proxy).Close();
                }
            }
            ColorConsole.WriteLine("完成");
        }
    }
}