Example #1
0
        /// <summary>
        /// Desativar - Remove servico do localizador e WCF
        /// </summary>
        public void Desativar()
        {
            try
            {
                // Desregistra do localizador
                if (this.ServicoInfo.RegistrarLocalizador)
                {
                    foreach (Type iface in this._interfaces)
                    {
                        LocalizadorCliente.Remover(iface);
                    }
                }

                // Desregistra o canal de comunicacao
                if (this.ServicoInfo.AtivarWCF)
                {
                    // Desregistra WCF
                    if (this.Host.State != CommunicationState.Closed)
                    {
                        this.Host.Close();
                    }
                }

                bAtivado = false;
            }
            catch (Exception ex)
            {
                logger.Error("Erro em Servico.Desativar(): ", ex);
            }
        }
Example #2
0
        public void Desativar()
        {
            try
            {
                // Desregistra do localizador
                if (this.ServicoInfo.RegistrarLocalizador)
                {
                    LocalizadorCliente.Remover(this.Interface);
                }

                // Desregistra o canal de comunicacao
                if (this.ServicoInfo.AtivarWCF)
                {
                    // Desregistra WCF
                    this.Host.Close();
                }
            }
            catch (Exception ex)
            {
                Log.EfetuarLog(ex, null, "OMS.Library.Servicos");
                throw ex;
            }
        }
Example #3
0
        public void Ativar()
        {
            try
            {
                // Cria o tipo da interface
                Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
                foreach (Assembly assembly in assemblies)
                {
                    this.Interface = assembly.GetType(this.ServicoInfo.NomeInterface);
                    if (this.Interface != null)
                    {
                        break;
                    }
                }

                // ATP: verificar esse ponto: se nao achou a interface, nao deve continuar aqui.
                // Tem instancia criada?
                if (this.Instancia == null)
                {
                    this.TipoInstancia = Type.GetType(this.ServicoInfo.NomeInstancia);
                    this.Instancia     = Activator.CreateInstance(this.TipoInstancia);
                }

                // Registra o canal de comunicação se necessário (casos de wcf)
                if (this.ServicoInfo.AtivarWCF)
                {
                    // Faz a ativação WCF
                    this.Host             = new ServiceHost(this.Instancia);
                    this.Host.OpenTimeout = new TimeSpan(0, 2, 0);

                    //ATP: Adicionando informacoes do MEX
                    ServiceMetadataBehavior metadataBehavior;
                    metadataBehavior = this.Host.Description.Behaviors.Find <ServiceMetadataBehavior>();
                    if (metadataBehavior == null)
                    {
                        metadataBehavior = new ServiceMetadataBehavior();
                        this.Host.Description.Behaviors.Add(metadataBehavior);
                    }

                    // Para cada endpoint do wcf, cria na colecao do ServicoInfo para publicar no localizador
                    foreach (System.ServiceModel.Description.ServiceEndpoint endPoint in this.Host.Description.Endpoints)
                    {
                        this.ServicoInfo.EndPoints.Add(
                            new ServicoEndPointInfo()
                        {
                            Endereco        = endPoint.Address.Uri.ToString(),
                            NomeBindingType = endPoint.Binding.GetType().FullName
                        });
                        //foreach (ServicoEndPointInfo sei in this.ServicoInfo.EndPoints)
                        //{
                        //    Binding binding = (Binding)typeof(BasicHttpBinding).Assembly.CreateInstance(sei.NomeBindingType);
                        //    binding.ReceiveTimeout = new TimeSpan(1, 0, 0);
                        //    this.Host.AddServiceEndpoint(this.Interface, binding, new Uri(sei.Endereco));
                        //}
                    }


                    // Inicia o ServiceHost
                    this.Host.Open();
                }

                // Registra no localizador se necessário
                if (this.ServicoInfo.RegistrarLocalizador)
                {
                    LocalizadorCliente.Registrar(this.ServicoInfo);
                }
            }
            catch (Exception ex)
            {
                Log.EfetuarLog(ex, null, "OMS.Library.Servicos");
                throw ex;
            }
        }
Example #4
0
        public static T Get <T>(ICallbackEvento callback, object parametros)
        {
            try
            {
                // Pega config
                if (_config == null)
                {
                    _config = GerenciadorConfig.ReceberConfig <AtivadorConfig>();
                }

                // Pega config do host, caso exista
                if (_configServicoHost == null)
                {
                    if (ServicoHostColecao.Default.IdConfigCarregado != null)
                    {
                        _configServicoHost = GerenciadorConfig.ReceberConfig <ServicoHostConfig>(
                            ServicoHostColecao.Default.IdConfigCarregado);
                    }
                }

                // Inicializa
                T           servico     = default(T);
                Type        tipo        = typeof(T);
                ServicoInfo servicoInfo = null;

                // Verifica se tem no cache
                bool adicionarNoCache = false;
                if (_cache.ContainsKey(typeof(T)))
                {
                    servicoInfo = _cache[typeof(T)];
                }
                else
                {
                    adicionarNoCache = true;
                }

                // Verifica se tem na lista interna
                if (servicoInfo == null && _config != null)
                {
                    servicoInfo = (from s in _config.Servicos
                                   where s.NomeInterface.StartsWith(tipo.FullName)
                                   select s).FirstOrDefault();
                }

                // Verifica se tem na lista de servicos do host
                if (servicoInfo == null && _configServicoHost != null)
                {
                    servicoInfo = (from s in _configServicoHost.Servicos
                                   where s.NomeInterface.StartsWith(tipo.FullName)
                                   select s).FirstOrDefault();
                }

                // Se ainda não achou, pega serviço info no localizador
                if (servicoInfo == null)
                {
                    servicoInfo = LocalizadorCliente.Consultar(typeof(T));
                }

                // Se até este ponto não achou o serviçoInfo, dispara erro
                if (servicoInfo == null)
                {
                    throw new Exception("Não foi possível conseguir informações para a ativação do serviço " + tipo.FullName + ".");
                }

                // Verifica se deve adicionar no cache
                if (adicionarNoCache && servicoInfo != null)
                {
                    _cache.Add(typeof(T), servicoInfo);
                }

                // Primeira tentativa deve ser criação local?
                if (servicoInfo.AtivacaoDefaultTipo == ServicoAtivacaoTipo.Local)
                {
                    // Cria o serviço
                    servico = ServicoHostColecao.Default.ReceberServico <T>();

                    // Caso seja servico com callback, faz a chamada do registro
                    IServicoComCallback servicoComCallback = servico as IServicoComCallback;
                    if (servicoComCallback != null && callback != null)
                    {
                        servicoComCallback.Registrar(parametros, callback);
                    }
                }

                if (servico == null && servicoInfo.EndPoints.Count > 0)
                {
                    // Cria via wcf
                    Binding binding =
                        (Binding)
                        typeof(BasicHttpBinding).Assembly.CreateInstance(
                            servicoInfo.EndPoints[0].NomeBindingType);
                    binding.ReceiveTimeout = new TimeSpan(0, 2, 0);
                    binding.SendTimeout    = new TimeSpan(0, 1, 0);
                    binding.OpenTimeout    = new TimeSpan(0, 0, 30);
                    binding.CloseTimeout   = new TimeSpan(0, 0, 30);
                    ((NetTcpBinding)binding).MaxReceivedMessageSize = 8000000;

                    // ATP: nao eh "tem contrato", e sim "tem callback"
                    // ATP: considerar isso em todo o trecho abaixo.

                    // Verifica se tem contrato
                    // Mesmo que não tenha informado, tem que ver se tem contrato especificado na interface
                    bool temContrato = callback != null;
                    if (!temContrato)
                    {
                        object[] attrs = typeof(T).GetCustomAttributes(typeof(ServiceContractAttribute), true);
                        if (attrs.Length == 1)
                        {
                            if (((ServiceContractAttribute)attrs[0]).CallbackContract != null)
                            {
                                temContrato = true;
                            }
                        }
                    }

                    // Cria dependendo se tem contrato ou não
                    if (!temContrato)
                    {
                        IChannelFactory <T> canal = new ChannelFactory <T>(binding);
                        servico =
                            canal.CreateChannel(
                                new EndpointAddress(
                                    servicoInfo.EndPoints[0].Endereco));
                    }
                    else
                    {
                        DuplexChannelFactory <T> canal = null;
                        if (callback != null)
                        {
                            canal = new DuplexChannelFactory <T>(new InstanceContext(callback), binding);
                        }
                        else
                        {
                            throw new Exception("Contratos que recebem callbacks tem necessariamente que receber um objeto de callback.");
                        }
                        servico =
                            canal.CreateChannel(
                                new EndpointAddress(
                                    servicoInfo.EndPoints[0].Endereco));

                        IServicoComCallback servicoComCallback = servico as IServicoComCallback;
                        if (servicoComCallback != null)
                        {
                            servicoComCallback.Registrar(parametros);
                        }
                    }

                    ((IContextChannel)servico).OperationTimeout = new TimeSpan(0, 10, 0);
                }

                // Retorna
                return(servico);
            }
            catch (Exception ex)
            {
                Log.EfetuarLog(ex, "typeof(T): " + typeof(T).FullName, "OMS.Library.Servicos");
                throw ex;
            }
        }
Example #5
0
        /// <summary>
        /// Ativar() - Cria instancia do servico, para uso local ou como WCF
        /// </summary>
        public void Ativar()
        {
            bool bSingleton = false;

            try
            {
                if (bAtivado)
                {
                    logger.Info("Servico já ativado por outra interface, ignorando");
                    return;
                }


                // Cria o tipo da interface
                Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
                foreach (string nomeInterface in this.ServicoInfo.NomeInterface)
                {
                    logger.Debug("Servico.Ativar(): procurando interface nos assemblies:" + nomeInterface);
                    foreach (Assembly assembly in assemblies)
                    {
                        Type Interface = assembly.GetType(nomeInterface);
                        if (Interface != null)
                        {
                            _interfaces.Add(Interface);
                        }
                    }
                }

                // Melhorar....
                if (_interfaces.Count == 0 || _interfaces.Count < this.ServicoInfo.NomeInterface.Count)
                {
                    foreach (string nomeInterface in this.ServicoInfo.NomeInterface)
                    {
                        logger.Info("Interface " + nomeInterface + " nao encontrada direto, usando Type.GetType()");
                        Type Interface = Type.GetType(nomeInterface);
                        if (Interface != null)
                        {
                            _interfaces.Add(Interface);
                        }
                        else
                        {
                            logger.Error("Interface " + nomeInterface + " nao encontrada em nenhum dos assemblies.");
                            return;
                        }
                    }
                }

                if (this.ServicoInfo.NomeInstancia == null || this.ServicoInfo.NomeInstancia.Length == 0)
                {
                    throw new Exception("Erro em Ativar(): Nome da instancia nao pode ser nula! Verifique a tag <NomeInstancia>");
                }


                // ATP: verificar esse ponto: se nao achou a interface, nao deve continuar aqui.
                // Tem instancia criada?
                if (this.Instancia == null)
                {
                    this.TipoInstancia = Type.GetType(this.ServicoInfo.NomeInstancia);
                    if (this.TipoInstancia != null)
                    {
                        this.Instancia = Activator.CreateInstance(this.TipoInstancia);
                    }
                    else
                    {
                        string msg = "Ativar(): ClassType da instancia nao encontrado para " + this.ServicoInfo.NomeInstancia;
                        msg += "\nVerifique Assemblies/Namespace da classe: " + this.ServicoInfo.NomeInstancia;
                        throw new Exception(msg);
                    }
                }

                // Registra o canal de comunicação se necessário (casos de wcf)
                if (this.ServicoInfo.AtivarWCF && this.Instancia != null)
                {
                    logger.Info("Ativando " + this.ServicoInfo.NomeInstancia + " como WCF");

                    ServiceBehaviorAttribute [] srvbehavior = this.Instancia.GetType().GetCustomAttributes(typeof(ServiceBehaviorAttribute), true) as ServiceBehaviorAttribute[];
                    if (srvbehavior != null && srvbehavior.Length > 0)
                    {
                        foreach (ServiceBehaviorAttribute attribute in srvbehavior)
                        {
                            logger.Info("InstanceContextMode : " + attribute.InstanceContextMode.ToString());
                            if (attribute.InstanceContextMode == InstanceContextMode.Single)
                            {
                                bSingleton = true;
                                logger.Info("ConcurrencyMode: " + attribute.ConcurrencyMode.ToString());
                                //if (attribute.ConcurrencyMode == ConcurrencyMode.Single)
                                //{
                                //    attribute.ConcurrencyMode = ConcurrencyMode.Multiple;
                                //    logger.Info("Novo ConcurrencyMode: " + attribute.ConcurrencyMode.ToString());
                                //}
                            }
                            else
                            {
                                logger.Warn("********************************************************");
                                logger.Warn("InstanceContextMode para a classe " + this.ServicoInfo.NomeInstancia);
                                logger.Warn("Esta definida como: " + attribute.InstanceContextMode.ToString());
                                logger.Warn("NÃO É UM SINGLETON!!! VERIFIQUE SE SUA CLASSE FOI PENSADA");
                                logger.Warn("PARA TER MAIS DE UMA INSTANCIA ATIVA");
                                logger.Warn("********************************************************");
                            }
                        }
                    }

                    // Faz a ativação WCF
                    if (bSingleton)
                    {
                        this.Host = new ServiceHost(this.Instancia);
                    }
                    else
                    {
                        this.Host = new ServiceHost(this.Instancia.GetType());
                    }
                    this.Host.OpenTimeout = new TimeSpan(0, 2, 0);
                    this.Host.Faulted    += new EventHandler(_hostFaulted);

                    logger.Info("Adicionando MetaData Behavior para " + this.ServicoInfo.NomeInstancia);

                    //ATP: Adicionando informacoes do MEX
                    ServiceMetadataBehavior metadataBehavior;
                    metadataBehavior = this.Host.Description.Behaviors.Find <ServiceMetadataBehavior>();
                    if (metadataBehavior == null)
                    {
                        logger.Info("Criando MetaData Behavior para " + this.ServicoInfo.NomeInstancia);
                        metadataBehavior = new ServiceMetadataBehavior();
                        string mexendpointaddr = this.MexBaseAddress + "/" + this.Instancia.ToString();
                        metadataBehavior.HttpGetUrl     = new Uri(mexendpointaddr);
                        metadataBehavior.HttpGetEnabled = true;
                        this.Host.Description.Behaviors.Add(metadataBehavior);
                    }


                    // Se configurado, acrescenta as configurações de throttling
                    if (this.ServicoInfo.MaxConcurrentCalls > 0 &&
                        this.ServicoInfo.MaxConcurrentInstances > 0 &&
                        this.ServicoInfo.MaxConcurrentSessions > 0)
                    {
                        logger.Info("Adicionando ServiceThrottleBehavior para " + this.ServicoInfo.NomeInstancia);

                        ServiceThrottlingBehavior throttleBehavior = new ServiceThrottlingBehavior();
                        throttleBehavior.MaxConcurrentCalls     = this.ServicoInfo.MaxConcurrentCalls.Value;
                        throttleBehavior.MaxConcurrentInstances = this.ServicoInfo.MaxConcurrentInstances.Value;
                        throttleBehavior.MaxConcurrentSessions  = this.ServicoInfo.MaxConcurrentSessions.Value;
                        logger.Info("MaxConcurrentCalls ......: " + throttleBehavior.MaxConcurrentCalls);
                        logger.Info("MaxConcurrentInstances ..: " + throttleBehavior.MaxConcurrentInstances);
                        logger.Info("MaxConcurrentSessions ...: " + throttleBehavior.MaxConcurrentSessions);

                        this.Host.Description.Behaviors.Add(throttleBehavior);
                    }


                    logger.Info("Adicionando ErrorServiceBehavior para " + this.ServicoInfo.NomeInstancia);
                    this.Host.Description.Behaviors.Add(new ErrorServiceBehavior());

                    logger.Info("Configurando ServiceDebugBehavior para " + this.ServicoInfo.NomeInstancia);
                    ServiceDebugBehavior debugBehavior = this.Host.Description.Behaviors.Find <ServiceDebugBehavior>();
                    if (debugBehavior != null)
                    {
                        debugBehavior.IncludeExceptionDetailInFaults = true;
                    }
                    else
                    {
                        debugBehavior = new ServiceDebugBehavior();
                        debugBehavior.IncludeExceptionDetailInFaults = true;
                        this.Host.Description.Behaviors.Add(debugBehavior);
                    }

                    // Cria endpoint se nao tiver algum definido no app.config
                    logger.Info("Adicionando endpoints para " + this.ServicoInfo.NomeInstancia);
                    if (this.Host.Description.Endpoints.Count == 0)
                    {
                        logger.Info("Nenhum endpoint declarado para o servico : " + this.ServicoInfo.NomeInstancia);

                        foreach (string baseAddress in this.BaseAddress)
                        {
                            Binding tcpBinding = null;

#if PRIVILEDGED_NAMED_PIPE
                            // NAO REMOVER O CODIGO ABAIXO
                            // PODERA SER USADO PARA ESCALAR A CAPACIDADE DO AMBIENTE
                            if (!baseAddress.StartsWith("net.pipe"))
                            {
                                tcpBinding = Utilities.GetBinding(baseAddress);
                            }
                            else
                            {
                                Process myproc = Process.GetCurrentProcess();

                                // Get the privileges and associated attributes.
                                PrivilegeAndAttributesCollection privileges = myproc.GetPrivileges();

                                //int maxPrivilegeLength = privileges..Max(privilege => privilege.Privilege.ToString().Length);

                                foreach (PrivilegeAndAttributes privilegeAndAttributes in privileges)
                                {
                                    // The privilege.
                                    Privilege privilege = privilegeAndAttributes.Privilege;

                                    // The privilege state.
                                    PrivilegeState privilegeState = privilegeAndAttributes.PrivilegeState;

                                    // Write out the privilege and its state.
                                    logger.DebugFormat(
                                        "{0}{1} => {2}",
                                        privilege,
                                        privilege.ToString(),
                                        privilegeState);
                                }


                                // Enable the TakeOwnership privilege on it.
                                AdjustPrivilegeResult result = myproc.EnablePrivilege(Privilege.CreateGlobal);

                                tcpBinding = new AclSecuredNamedPipeBinding();

                                try
                                {
                                    SecurityIdentifier allow = (SecurityIdentifier)(new NTAccount("Everyone").Translate(typeof(SecurityIdentifier)));

                                    ((AclSecuredNamedPipeBinding)tcpBinding).AddUserOrGroup(allow);
                                }
                                catch (Exception ex)
                                {
                                    logger.Error(ex);
                                }

                                try
                                {
                                    SecurityIdentifier allow = (SecurityIdentifier)(new NTAccount("Todos").Translate(typeof(SecurityIdentifier)));

                                    ((AclSecuredNamedPipeBinding)tcpBinding).AddUserOrGroup(allow);
                                }
                                catch (Exception ex)
                                {
                                    logger.Error(ex);
                                }

                                logger.Debug("Apos setar privilegios");
                                // Get the privileges and associated attributes.
                                privileges = myproc.GetPrivileges();


                                foreach (PrivilegeAndAttributes privilegeAndAttributes in privileges)
                                {
                                    // The privilege.
                                    Privilege privilege = privilegeAndAttributes.Privilege;

                                    // The privilege state.
                                    PrivilegeState privilegeState = privilegeAndAttributes.PrivilegeState;

                                    // Write out the privilege and its state.
                                    logger.DebugFormat(
                                        "{0}{1} => {2}",
                                        privilege,
                                        privilege.ToString(),
                                        privilegeState);
                                }
                            }
#else
                            tcpBinding = Utilities.GetBinding(baseAddress);
#endif
                            foreach (Type iface in this._interfaces)
                            {
                                string endpointaddr = baseAddress + "/" + iface.ToString();

                                logger.Info("Criando endpoint: Interface=[" + iface.ToString() + "]  Instancia=[" + this.Instancia.ToString() + "] Address=[" + endpointaddr + "]");

                                this.Host.AddServiceEndpoint(iface, tcpBinding, endpointaddr);
                            }
                        }
                    }

                    // Adiciona o enpoint MEX para o fim da lista
                    logger.Info("Criando endpoint MEX para " + this.ServicoInfo.NomeInstancia);
                    this.Host.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), this.MexBaseAddress + "/" + this.Instancia.ToString());

                    // Popula as informacoes dos endpoints para o servico Localizador
                    // Ver Ativador.Get<>()
                    if (this.Host.Description.Endpoints.Count > 0)
                    {
                        // Para cada endpoint do wcf, cria na colecao do ServicoInfo para publicar no localizador
                        foreach (System.ServiceModel.Description.ServiceEndpoint endPoint in this.Host.Description.Endpoints)
                        {
                            logger.Info("Verificando validade do endpoint [" + endPoint.Address.Uri.ToString() + "] tipo: [" + endPoint.Binding.GetType().FullName + "] para localizador");

                            if (endPoint.Address.Uri.ToString().Contains("/MEX") == false)
                            {
                                logger.Info("Adicionando informacoes do endpoint [" + endPoint.Address.Uri.ToString() + "] tipo: [" + endPoint.Binding.GetType().FullName + "] para localizador");
                                this.ServicoInfo.EndPoints.Add(
                                    new ServicoEndPointInfo()
                                {
                                    Endereco = endPoint.Address.Uri.ToString(),
                                    //NomeBindingType = endPoint.Binding.GetType().FullName
                                    NomeBindingType = Utilities.GetBindingType(endPoint.Address.Uri.ToString())
                                });
                            }

                            ContractDescription cd = endPoint.Contract;

                            foreach (OperationDescription od in cd.Operations)
                            {
                                DataContractSerializerOperationBehavior serializerBh = od.Behaviors.Find <DataContractSerializerOperationBehavior>();
                                if (serializerBh == null)
                                {
                                    logger.Info("Adicionando DataContractSerializerOperationBehavior");
                                    serializerBh = new DataContractSerializerOperationBehavior(od);
                                    od.Behaviors.Add(serializerBh);
                                }

                                logger.Info("Setando MaxItemsInObjectGraph para operacao: " + od.Name);
                                serializerBh.MaxItemsInObjectGraph = 8000000;
                            }
                        }
                    }

                    logger.Info("Servico: " + this.ServicoInfo.NomeInstancia + " opening host...");

                    // Inicia o ServiceHost
                    this.Host.Open();
                }

                // Marca servico como ativo.
                bAtivado = true;

                // Registra no localizador se necessário
                if (this.ServicoInfo.RegistrarLocalizador)
                {
                    logger.Info("Registrando servico no Localizador");
                    LocalizadorCliente.Registrar(this.ServicoInfo);
                }

                logger.Info("***");
                logger.Info("   ");
            }
            catch (Exception ex)
            {
                logger.Error("Erro em Servico.Ativar(): ", ex);
                throw ex;
            }
        }
Example #6
0
        public static T Get <T>(ICallbackEvento callback, object parametros)
        {
            try
            {
                logger.Info("Ativador.Get<" + typeof(T).ToString() + ">()");

                // Pega config
                if (_config == null)
                {
                    _config = GerenciadorConfig.ReceberConfig <AtivadorConfig>();
                }

                // Pega config do host, caso exista
                if (_configServicoHost == null)
                {
                    if (ServicoHostColecao.Default.IdConfigCarregado != null)
                    {
                        _configServicoHost = GerenciadorConfig.ReceberConfig <ServicoHostConfig>(
                            ServicoHostColecao.Default.IdConfigCarregado);
                    }
                }

                // Inicializa
                T           servico     = default(T);
                Type        tipo        = typeof(T);
                ServicoInfo servicoInfo = null;

                // Verifica se tem no cache
                bool adicionarNoCache = false;
                lock (_cache)
                {
                    if (_cache.ContainsKey(typeof(T)))
                    {
                        servicoInfo = _cache[typeof(T)];
                    }
                    else
                    {
                        adicionarNoCache = true;
                    }
                }

                // Verifica se tem na lista interna
                if (servicoInfo == null && _config != null)
                {
                    logger.Info("Buscando informacoes do servico " + tipo.FullName + " na lista interna");
                    servicoInfo = _findServicoInfo(tipo.FullName, _config.Servicos);
                }

                // Verifica se tem na lista de servicos do host
                if (servicoInfo == null && _configServicoHost != null)
                {
                    logger.Info("Buscando informacoes do servico " + tipo.FullName + " na lista de servicos do host");
                    servicoInfo = _findServicoInfo(tipo.FullName, _configServicoHost.Servicos);
                }

                // Se ainda não achou, pega serviço info no localizador
                if (servicoInfo == null)
                {
                    logger.Info("Buscando informacoes do servico " + tipo.FullName + " no localizador");
                    servicoInfo = LocalizadorCliente.Consultar(typeof(T));
                }

                // Se até este ponto não achou o serviçoInfo, dispara erro
                if (servicoInfo == null)
                {
                    logger.Error("Não foi possível conseguir informações para a ativação do serviço " + tipo.FullName);

                    throw new Exception("Não foi possível conseguir informações para a ativação do serviço " + tipo.FullName + ".");
                }

                // Verifica se deve adicionar no cache
                if (adicionarNoCache && servicoInfo != null)
                {
                    lock (_cache)
                    {
                        if (!_cache.ContainsKey(typeof(T)))
                        {
                            logger.Info("Armazenando informacoes do servico " + tipo.FullName + " no cache");
                            _cache.Add(typeof(T), servicoInfo);
                        }
                    }
                }

                // Primeira tentativa deve ser criação local?
                if (servicoInfo.AtivacaoDefaultTipo == ServicoAtivacaoTipo.Local)
                {
                    logger.Debug("Ativando " + tipo.FullName + " localmente");

                    // Cria o serviço
                    servico = ServicoHostColecao.Default.ReceberServico <T>();

                    // Caso seja servico com callback, faz a chamada do registro
                    IServicoComCallback servicoComCallback = servico as IServicoComCallback;
                    if (servicoComCallback != null && callback != null)
                    {
                        servicoComCallback.Registrar(parametros, callback);
                    }
                }

                if (servico == null && servicoInfo.EndPoints.Count > 0)
                {
                    ContractDescription cd;
                    logger.Debug("Ativando " + tipo.FullName + " como WCF");

                    string epaddress = _findEndpointForInterface <T>(servicoInfo);

                    logger.Debug("Criando Binding para Endpoint: " + epaddress);

                    // Cria via wcf
                    Binding binding = Utilities.GetBinding(epaddress);
                    //(Binding)
                    //    typeof(BasicHttpBinding).Assembly.CreateInstance(
                    //        servicoInfo.EndPoints[0].NomeBindingType);
                    binding.ReceiveTimeout = new TimeSpan(0, 2, 0);
                    binding.SendTimeout    = new TimeSpan(0, 1, 0);
                    binding.OpenTimeout    = new TimeSpan(0, 0, 30);
                    binding.CloseTimeout   = new TimeSpan(0, 0, 30);
                    if (servicoInfo.EndPoints[0].NomeBindingType.Equals("System.ServiceModel.NetTcpBinding"))
                    {
                        ((NetTcpBinding)binding).MaxReceivedMessageSize = 8000000;
                        ((NetTcpBinding)binding).ReaderQuotas           = System.Xml.XmlDictionaryReaderQuotas.Max;
                        //((NetTcpBinding)binding).Security.Mode = SecurityMode.None;
                    }

                    if (servicoInfo.EndPoints[0].NomeBindingType.Equals("System.ServiceModel.BasicHttpBinding"))
                    {
                        logger.Debug("Binding setado BasicHttpBinding , verificando por callback");

                        ((BasicHttpBinding)binding).MaxReceivedMessageSize = int.MaxValue;
                        ((BasicHttpBinding)binding).ReaderQuotas           = System.Xml.XmlDictionaryReaderQuotas.Max;
                        //((NetTcpBinding)binding).Security.Mode = SecurityMode.None;
                    }



                    logger.Debug("Binding criado, verificando por callback");

                    // Verifica se tem callback
                    // Mesmo que não tenha informado, tem que ver se tem contrato especificado na interface
                    bool temCallback = callback != null;
                    if (!temCallback)
                    {
                        object[] attrs = typeof(T).GetCustomAttributes(typeof(ServiceContractAttribute), true);
                        if (attrs.Length == 1)
                        {
                            if (((ServiceContractAttribute)attrs[0]).CallbackContract != null)
                            {
                                temCallback = true;
                            }
                        }
                    }

                    // Cria dependendo se tem contrato ou não
                    if (!temCallback)
                    {
                        logger.Debug("Servico " + tipo.FullName + " nao tem callback, criando channel ");

                        IChannelFactory <T> canal = new ChannelFactory <T>(binding);
                        canal.Faulted += new EventHandler(_channelFaulted);
                        string uri = _findEndpointForInterface <T>(servicoInfo);
                        if (uri == null)
                        {
                            string msg = "Servico [" + tipo.FullName + "] nao pôde ser ativado.\n";
                            msg += "Verifique se existe <ServicoEndPointInfo> nas configuracoes locais,\n";
                            msg += "ou se um endpoint foi criado para o mesmo e registrado no ServicoLocalizador.";

                            logger.Error("ERRO: NENHUM ENDERECO DE ENDPOINT PARA SERVICO [" + tipo.FullName + "]!");
                            throw new Exception(msg);
                        }

                        servico = canal.CreateChannel(new EndpointAddress(uri));

                        cd = ((ChannelFactory)canal).Endpoint.Contract;
                    }
                    else
                    {
                        logger.Debug("Servico " + tipo.FullName + " tem callback, criando channel duplex");

                        DuplexChannelFactory <T> canal = null;
                        canal.Faulted += new EventHandler(_channelFaulted);
                        if (callback == null)
                        {
                            logger.Error("Contratos que recebem callbacks tem necessariamente que receber um objeto de callback.");

                            throw new Exception("Contratos que recebem callbacks tem necessariamente que receber um objeto de callback.");
                        }

                        canal = new DuplexChannelFactory <T>(new InstanceContext(callback), binding);
                        string uri = _findEndpointForInterface <T>(servicoInfo);
                        if (uri == null)
                        {
                            string msg = "Servico [" + tipo.FullName + "] nao pôde ser ativado.\n";
                            msg += "Verifique se existe <ServicoEndPointInfo> nas configuracoes locais,\n";
                            msg += "ou se um endpoint foi criado para o mesmo e registrado no ServicoLocalizador.";

                            logger.Error("ERRO: NENHUM ENDERECO DE ENDPOINT PARA SERVICO [" + tipo.FullName + "]!");
                            throw new Exception(msg);
                        }
                        servico = canal.CreateChannel(new EndpointAddress(uri));

                        cd = canal.Endpoint.Contract;


                        IServicoComCallback servicoComCallback = servico as IServicoComCallback;
                        if (servicoComCallback != null)
                        {
                            servicoComCallback.Registrar(parametros);
                        }
                    }

                    if (cd != null)
                    {
                        foreach (OperationDescription od in cd.Operations)
                        {
                            DataContractSerializerOperationBehavior serializerBh = od.Behaviors.Find <DataContractSerializerOperationBehavior>();
                            if (serializerBh == null)
                            {
                                logger.Info("Adicionando DataContractSerializerOperationBehavior");
                                serializerBh = new DataContractSerializerOperationBehavior(od);
                                od.Behaviors.Add(serializerBh);
                            }

                            logger.Info("Setando MaxItemsInObjectGraph para operacao: " + od.Name);
                            serializerBh.MaxItemsInObjectGraph = 8000000;
                        }
                    }
                    ((IContextChannel)servico).OperationTimeout = new TimeSpan(0, 10, 0);
                }

                if (servico == null)
                {
                    string msg = "Servico [" + tipo.FullName + "] nao pôde ser ativado.\n";
                    msg += "Verifique se existe <servicoinfo> nas configuracoes locais,\n";
                    msg += "ou se o mesmo foi registrado no ServicoLocalizador e seu hoster esta ativo.";

                    logger.Error("ERRO: SERVICO [" + tipo.FullName + "] NAO FOI ATIVADO!!!");
                    throw new Exception(msg);
                }

                // Retorna
                return(servico);
            }
            catch (Exception ex)
            {
                logger.Error("Erro em Ativador.Get(" + typeof(T).FullName + ")", ex);
                throw ex;
            }
        }