扩展ServiceHost<T>类

  public class ServiceHost<T> : ServiceHost
    {

        public void EnableMetadataExchange(bool enableHttpGet = true)
        {
            if (State == CommunicationState.Opened)
            {
                throw new InvalidOperationException("Host is already opened");
            }

            var metadataBehavior = Description.Behaviors.Find<ServiceMetadataBehavior>();
            if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceMetadataBehavior();
                Description.Behaviors.Add(metadataBehavior);

                if (BaseAddresses.Any(uri => uri.Scheme == "http"))
                {
                    metadataBehavior.HttpGetEnabled = enableHttpGet;
                }
            }

            AddAllMexEndpoints();
        }

        public bool HasMexEndpoint
        {
            get
            {
                return
                    Description.Endpoints.Any(endpoint => endpoint.Contract.ContractType == typeof (IMetadataExchange));
            }
        }

        public void AddAllMexEndpoints()
        {
            Debug.Assert(HasMexEndpoint == false);

            foreach (var baseAddress in BaseAddresses)
            {
                Binding binding = null;

                switch (baseAddress.Scheme)
                {
                    case "net.tcp":
                        binding = MetadataExchangeBindings.CreateMexTcpBinding();
                        break;
                    case "net.pipe":
                        binding = MetadataExchangeBindings.CreateMexNamedPipeBinding();
                        break;
                    case "http":
                        binding = MetadataExchangeBindings.CreateMexHttpBinding();
                        break;
                    case "https":
                        binding = MetadataExchangeBindings.CreateMexHttpsBinding();
                        break;
                }

                if (binding != null)
                {
                    AddServiceEndpoint(typeof(IMetadataExchange),binding,"MEX");
                }
            }
        }

    }

 

posted @ 2013-11-04 21:35  Mind-Hacker  阅读(300)  评论(0编辑  收藏  举报