void LoadInputParametersIntoLocals(ParameterInfo[] parameters, LocalBuilder[] parameterLocals, ArgBuilder inputParametersArg, out int inputParameterCount)
 {
     inputParameterCount = 0;
     for (int i = 0; i < parameterLocals.Length; i++)
     {
         if (ServiceReflector.FlowsIn(parameters[i]))
         {
             Type parameterType = parameterLocals[i].LocalType;
             ilg.LoadArrayElement(inputParametersArg, inputParameterCount);
             if (!parameterType.IsValueType)
             {
                 ilg.ConvertValue(TypeOfObject, parameterType);
                 ilg.Store(parameterLocals[i]);
             }
             else
             {
                 ilg.Dup();
                 ilg.If();
                 ilg.ConvertValue(TypeOfObject, parameterType);
                 ilg.Store(parameterLocals[i]);
                 ilg.Else();
                 ilg.Pop();
                 ilg.LoadZeroValueIntoLocal(parameterType, parameterLocals[i]);
                 ilg.EndIf();
             }
             inputParameterCount++;
         }
     }
 }
        private void CreateInArgs()
        {
            var parameters = MethodBase.GetParameters();
            int inCount    = 0;

            foreach (var param in parameters)
            {
                if (ServiceReflector.FlowsIn(param))
                {
                    inCount++;
                }
            }

            if (inCount == Args.Length) // All parameters are InArgs so do nothing and fallback to returning Args
            {
                return;
            }

            _inArgs = new object[inCount];
            int inPos = 0;

            for (int argPos = 0; argPos < parameters.Length; argPos++)
            {
                if (ServiceReflector.FlowsIn(parameters[argPos]))
                {
                    _inArgs[inPos] = Args[argPos];
                    inPos++;
                }
            }

            Fx.Assert((inPos - 1) != (inCount), $"Incorrect number of arguments put into _inArgs array, expected {inCount} and copied {inPos - 1}");
        }
Exemple #3
0
        private void contextMenuServiceConnect_Click(object sender, EventArgs e)
        {
            XElement description = null;

            DoService(data =>
            {
                description = data.Service.Callback.GetServiceDescription();
            });

            if (description != null)
            {
                try
                {
                    ServiceReflector reflector = new ServiceReflector(description);
                    using (var form = new ServiceTestClientForm())
                    {
                        form.Reflector = reflector;
                        form.ShowDialog();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, this.Text);
                }
            }
        }
        internal ProxyOperationRuntime(ClientOperation operation, ImmutableClientRuntime parent)
        {
            if (operation == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operation");
            }
            if (parent == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
            }

            this.parent        = parent;
            this.formatter     = operation.Formatter;
            this.isInitiating  = operation.IsInitiating;
            this.isOneWay      = operation.IsOneWay;
            this.isTerminating = operation.IsTerminating;
            this.isSessionOpenNotificationEnabled = operation.IsSessionOpenNotificationEnabled;
            this.name = operation.Name;
            this.parameterInspectors = EmptyArray <IParameterInspector> .ToArray(operation.ParameterInspectors);

            this.faultFormatter   = operation.FaultFormatter;
            this.serializeRequest = operation.SerializeRequest;
            this.deserializeReply = operation.DeserializeReply;
            this.action           = operation.Action;
            this.replyAction      = operation.ReplyAction;
            this.beginMethod      = operation.BeginMethod;
            this.syncMethod       = operation.SyncMethod;
            this.taskMethod       = operation.TaskMethod;
            this.TaskTResult      = operation.TaskTResult;

            if (this.beginMethod != null)
            {
                this.inParams = ServiceReflector.GetInputParameters(this.beginMethod, true);
                if (this.syncMethod != null)
                {
                    this.outParams = ServiceReflector.GetOutputParameters(this.syncMethod, false);
                }
                else
                {
                    this.outParams = NoParams;
                }
                this.endOutParams = ServiceReflector.GetOutputParameters(operation.EndMethod, true);
                this.returnParam  = operation.EndMethod.ReturnParameter;
            }
            else if (this.syncMethod != null)
            {
                this.inParams    = ServiceReflector.GetInputParameters(this.syncMethod, false);
                this.outParams   = ServiceReflector.GetOutputParameters(this.syncMethod, false);
                this.returnParam = this.syncMethod.ReturnParameter;
            }

            if (this.formatter == null && (serializeRequest || deserializeReply))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ClientRuntimeRequiresFormatter0, this.name)));
            }
        }
Exemple #5
0
        internal ProxyOperationRuntime(ClientOperation operation, ImmutableClientRuntime parent)
        {
            if (operation == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operation");
            }
            if (parent == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
            }

            _parent        = parent;
            _formatter     = operation.Formatter;
            _isInitiating  = operation.IsInitiating;
            _isOneWay      = operation.IsOneWay;
            _isTerminating = operation.IsTerminating;
            _isSessionOpenNotificationEnabled = operation.IsSessionOpenNotificationEnabled;
            _name = operation.Name;
            _parameterInspectors = EmptyArray <IParameterInspector> .ToArray(operation.ParameterInspectors);

            _faultFormatter   = operation.FaultFormatter;
            _serializeRequest = operation.SerializeRequest;
            _deserializeReply = operation.DeserializeReply;
            _action           = operation.Action;
            _replyAction      = operation.ReplyAction;
            _beginMethod      = operation.BeginMethod;
            _syncMethod       = operation.SyncMethod;
            _taskMethod       = operation.TaskMethod;
            this.TaskTResult  = operation.TaskTResult;

            if (_beginMethod != null)
            {
                _inParams = ServiceReflector.GetInputParameters(_beginMethod, true);
                if (_syncMethod != null)
                {
                    _outParams = ServiceReflector.GetOutputParameters(_syncMethod, false);
                }
                else
                {
                    _outParams = Array.Empty <ParameterInfo>();
                }
                _endOutParams = ServiceReflector.GetOutputParameters(operation.EndMethod, true);
                _returnParam  = operation.EndMethod.ReturnParameter;
            }
            else if (_syncMethod != null)
            {
                _inParams    = ServiceReflector.GetInputParameters(_syncMethod, false);
                _outParams   = ServiceReflector.GetOutputParameters(_syncMethod, false);
                _returnParam = _syncMethod.ReturnParameter;
            }

            if (_formatter == null && (_serializeRequest || _deserializeReply))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientRuntimeRequiresFormatter0, _name)));
            }
        }
 void LoadZeroValueInputParametersIntoLocals(ParameterInfo[] parameters, LocalBuilder[] parameterLocals)
 {
     for (int i = 0; i < parameterLocals.Length; i++)
     {
         if (ServiceReflector.FlowsIn(parameters[i]))
         {
             ilg.LoadZeroValueIntoLocal(parameterLocals[i].LocalType, parameterLocals[i]);
         }
     }
 }
Exemple #7
0
 public static void CheckForDisposableParameters(OperationDescription operation, Type type)
 {
     if (type == null)
     {
         operation.HasNoDisposableParameters = true;
     }
     else
     {
         operation.HasNoDisposableParameters = !ServiceReflector.IsParameterDisposable(type);
     }
 }
 public static void CheckForDisposableParameters(OperationDescription operation, System.Type[] types)
 {
     operation.HasNoDisposableParameters = true;
     foreach (System.Type type in types)
     {
         if (ServiceReflector.IsParameterDisposable(type))
         {
             operation.HasNoDisposableParameters = false;
             return;
         }
     }
 }
Exemple #9
0
        public static void CheckForDisposableParameters(OperationDescription operation, Type[] types)
        {
            Fx.Assert(types != null, "Argument cannot be null!");

            operation.HasNoDisposableParameters = true;
            foreach (Type type in types)
            {
                if (ServiceReflector.IsParameterDisposable(type))
                {
                    operation.HasNoDisposableParameters = false;
                    break;
                }
            }
        }
 void LoadOutputParametersIntoArray(ParameterInfo[] parameters, LocalBuilder[] parameterLocals, ArgBuilder outputParametersArg, out int outputParameterCount)
 {
     outputParameterCount = 0;
     for (int i = 0; i < parameterLocals.Length; i++)
     {
         if (ServiceReflector.FlowsOut(parameters[i]))
         {
             ilg.Load(outputParametersArg);
             ilg.Load(outputParameterCount);
             ilg.Load(parameterLocals[i]);
             ilg.ConvertValue(parameterLocals[i].LocalType, TypeOfObject);
             ilg.Stelem(TypeOfObject);
             outputParameterCount++;
         }
     }
 }
Exemple #11
0
        private OperationDescription CreateOperationDescription(ContractDescription contract, System.Reflection.MethodInfo methodInfo, ComContractElement config, bool allowReferences)
        {
            System.ServiceModel.Description.XmlName methodName      = new System.ServiceModel.Description.XmlName(ServiceReflector.GetLogicalName(methodInfo));
            System.ServiceModel.Description.XmlName returnValueName = TypeLoader.GetReturnValueName(methodName);
            if (ServiceReflector.IsBegin(methodInfo))
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.NoAsyncOperationsAllowed());
            }
            if (contract.Operations.FindAll(methodName.EncodedName).Count != 0)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.DuplicateOperation());
            }
            OperationDescription description = new OperationDescription(methodName.EncodedName, contract)
            {
                SyncMethod    = methodInfo,
                IsInitiating  = true,
                IsTerminating = false
            };

            description.KnownTypes.Add(typeof(Array));
            description.KnownTypes.Add(typeof(DBNull));
            description.KnownTypes.Add(typeof(CurrencyWrapper));
            description.KnownTypes.Add(typeof(ErrorWrapper));
            if (allowReferences)
            {
                description.KnownTypes.Add(typeof(PersistStreamTypeWrapper));
            }
            foreach (ComUdtElement element in config.UserDefinedTypes)
            {
                Type type;
                Guid typeLibId = Fx.CreateGuid(element.TypeLibID);
                TypeCacheManager.Provider.FindOrCreateType(typeLibId, element.TypeLibVersion, Fx.CreateGuid(element.TypeDefID), out type, false);
                this.info.AddUdt(type, typeLibId);
                description.KnownTypes.Add(type);
            }
            string             ns           = contract.Namespace;
            XmlQualifiedName   contractName = new XmlQualifiedName(contract.Name, ns);
            string             action       = NamingHelper.GetMessageAction(contractName, methodName.DecodedName, null, false);
            string             str3         = NamingHelper.GetMessageAction(contractName, methodName.DecodedName, null, true);
            MessageDescription item         = this.CreateIncomingMessageDescription(contract, methodInfo, ns, action, allowReferences);
            MessageDescription description3 = this.CreateOutgoingMessageDescription(contract, methodInfo, returnValueName, ns, str3, allowReferences);

            description.Messages.Add(item);
            description.Messages.Add(description3);
            return(description);
        }
 MessageDescription CreateIncomingMessageDescription(ContractDescription contract,
                                                     MethodInfo methodInfo,
                                                     string ns,
                                                     string action,
                                                     bool allowReferences)
 {
     ParameterInfo[] parameters = ServiceReflector.GetInputParameters(methodInfo, false);
     return(CreateParameterMessageDescription(contract,
                                              parameters,
                                              null,
                                              null,
                                              null,
                                              methodInfo.Name,
                                              ns,
                                              action,
                                              MessageDirection.Input,
                                              allowReferences));
 }
 MessageDescription CreateOutgoingMessageDescription(ContractDescription contract,
                                                     MethodInfo methodInfo,
                                                     XmlName returnValueName,
                                                     string ns,
                                                     string action,
                                                     bool allowReferences)
 {
     ParameterInfo[] parameters = ServiceReflector.GetOutputParameters(methodInfo, false);
     return(CreateParameterMessageDescription(contract,
                                              parameters,
                                              methodInfo.ReturnType,
                                              methodInfo.ReturnTypeCustomAttributes,
                                              returnValueName,
                                              methodInfo.Name,
                                              ns,
                                              action,
                                              MessageDirection.Output,
                                              allowReferences));
 }
Exemple #14
0
        public static bool IsValidParameter(Type type, ICustomAttributeProvider attributeProvider, bool allowReferences)
        {
            foreach (MarshalAsAttribute attribute in ServiceReflector.GetCustomAttributes(attributeProvider, typeof(MarshalAsAttribute), true))
            {
                switch (attribute.Value)
                {
                case UnmanagedType.IDispatch:
                case UnmanagedType.Interface:
                case UnmanagedType.IUnknown:
                    return(allowReferences);
                }
            }
            XsdDataContractExporter exporter = new XsdDataContractExporter();

            if (!exporter.CanExport(type))
            {
                return(false);
            }
            return(true);
        }
Exemple #15
0
        private void buttonConnectRemoteService_Click(object sender, EventArgs e)
        {
            ListViewItem item = listViewRemoteServices.SelectedItems[0];
            string       url  = item.SubItems[1].Text;
            string       host = (string)item.Tag;

            QueryHttp(
                url,
                message =>
            {
                XElement description       = XElement.Parse(message);
                ServiceReflector reflector = new ServiceReflector(description);
                using (var form = new ServiceTestClientForm())
                {
                    form.Reflector = reflector;
                    form.Host      = host;
                    form.ShowDialog();
                }
            },
                () => { }
                );
        }
        protected override System.ServiceModel.Description.ServiceDescription CreateDescription(out IDictionary <string, ContractDescription> implementedContracts)
        {
            System.ServiceModel.Description.ServiceDescription service;
            if (this.serviceType == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxServiceHostCannotCreateDescriptionWithoutServiceType")));
            }
            if (this.SingletonInstance != null)
            {
                service = System.ServiceModel.Description.ServiceDescription.GetService(this.SingletonInstance);
            }
            else
            {
                service = System.ServiceModel.Description.ServiceDescription.GetService(this.serviceType);
            }
            ServiceBehaviorAttribute attribute = service.Behaviors.Find <ServiceBehaviorAttribute>();
            object wellKnownSingleton          = attribute.GetWellKnownSingleton();

            if (wellKnownSingleton == null)
            {
                wellKnownSingleton      = attribute.GetHiddenSingleton();
                this.disposableInstance = wellKnownSingleton as IDisposable;
            }
            if ((typeof(IServiceBehavior).IsAssignableFrom(this.serviceType) || typeof(IContractBehavior).IsAssignableFrom(this.serviceType)) && (wellKnownSingleton == null))
            {
                wellKnownSingleton      = System.ServiceModel.Description.ServiceDescription.CreateImplementation(this.serviceType);
                this.disposableInstance = wellKnownSingleton as IDisposable;
            }
            if ((this.SingletonInstance == null) && (wellKnownSingleton is IServiceBehavior))
            {
                service.Behaviors.Add((IServiceBehavior)wellKnownSingleton);
            }
            ReflectedContractCollection contracts  = new ReflectedContractCollection();
            List <System.Type>          interfaces = ServiceReflector.GetInterfaces(this.serviceType);

            for (int i = 0; i < interfaces.Count; i++)
            {
                System.Type key = interfaces[i];
                if (!contracts.Contains(key))
                {
                    ContractDescription item = null;
                    if (wellKnownSingleton != null)
                    {
                        item = ContractDescription.GetContract(key, wellKnownSingleton);
                    }
                    else
                    {
                        item = ContractDescription.GetContract(key, this.serviceType);
                    }
                    contracts.Add(item);
                    Collection <ContractDescription> inheritedContracts = item.GetInheritedContracts();
                    for (int j = 0; j < inheritedContracts.Count; j++)
                    {
                        ContractDescription description3 = inheritedContracts[j];
                        if (!contracts.Contains(description3.ContractType))
                        {
                            contracts.Add(description3);
                        }
                    }
                }
            }
            this.reflectedContracts = contracts;
            implementedContracts    = contracts.ToImplementedContracts();
            return(service);
        }
        //
        // Note - the code below this line a paraphrase of the SM reflection code in TypeLoader.cs
        // Ideally we would be re-using their code, but our assumptions are too disjoint
        // for that to be realistic at the time of writing (12/2004).
        //

        OperationDescription CreateOperationDescription(ContractDescription contract, MethodInfo methodInfo, ComContractElement config, bool allowReferences)
        {
            XmlName operationName   = new XmlName(ServiceReflector.GetLogicalName(methodInfo));
            XmlName returnValueName = TypeLoader.GetReturnValueName(operationName);

            if (ServiceReflector.IsBegin(methodInfo) || ServiceReflector.IsTask(methodInfo))
            {
                Fx.Assert("No async operations allowed");

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.NoAsyncOperationsAllowed());
            }
            if (contract.Operations.FindAll(operationName.EncodedName).Count != 0)
            {
                Fx.Assert("Duplicate operation name");

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.DuplicateOperation());
            }

            OperationDescription operationDescription = new OperationDescription(operationName.EncodedName, contract);

            operationDescription.SyncMethod    = methodInfo;
            operationDescription.IsInitiating  = true;
            operationDescription.IsTerminating = false;

            operationDescription.KnownTypes.Add(typeof(Array));
            operationDescription.KnownTypes.Add(typeof(DBNull));
            operationDescription.KnownTypes.Add(typeof(CurrencyWrapper));
            operationDescription.KnownTypes.Add(typeof(ErrorWrapper));

            if (allowReferences)
            {
                operationDescription.KnownTypes.Add(typeof(PersistStreamTypeWrapper));
            }

            foreach (ComUdtElement udt in config.UserDefinedTypes)
            {
                Type knownType;

                Guid typeLibID = Fx.CreateGuid(udt.TypeLibID);

                TypeCacheManager.Provider.FindOrCreateType(typeLibID, udt.TypeLibVersion, Fx.CreateGuid(udt.TypeDefID), out knownType, false);

                this.info.AddUdt(knownType, typeLibID);
                operationDescription.KnownTypes.Add(knownType);
            }


            string           ns            = contract.Namespace;
            XmlQualifiedName contractQName = new XmlQualifiedName(contract.Name, ns);

            string requestAction = NamingHelper.GetMessageAction(contractQName,
                                                                 operationName.DecodedName,
                                                                 null,
                                                                 false);

            string responseAction = NamingHelper.GetMessageAction(contractQName,
                                                                  operationName.DecodedName,
                                                                  null,
                                                                  true);

            MessageDescription inMessage = CreateIncomingMessageDescription(contract,
                                                                            methodInfo,
                                                                            ns,
                                                                            requestAction,
                                                                            allowReferences);

            MessageDescription outMessage = CreateOutgoingMessageDescription(contract,
                                                                             methodInfo,
                                                                             returnValueName,
                                                                             ns,
                                                                             responseAction,
                                                                             allowReferences);

            operationDescription.Messages.Add(inMessage);
            operationDescription.Messages.Add(outMessage);

            return(operationDescription);
        }
Exemple #18
0
            internal static InvokeDelegate GenerateInvokeDelegate(MethodInfo method, out int inputParameterCount, out int outputParameterCount)
            {
                ParameterInfo[] parameters   = method.GetParameters();
                bool            returnsValue = method.ReturnType != typeof(void);
                int             paramCount   = parameters.Length;

                var inputParamPositions  = new List <int>();
                var outputParamPositions = new List <int>();

                for (int i = 0; i < parameters.Length; i++)
                {
                    if (ServiceReflector.FlowsIn(parameters[i]))
                    {
                        inputParamPositions.Add(i);
                    }

                    if (ServiceReflector.FlowsOut(parameters[i]))
                    {
                        outputParamPositions.Add(i);
                    }
                }

                int[] inputPos  = inputParamPositions.ToArray();
                int[] outputPos = outputParamPositions.ToArray();

                inputParameterCount  = inputPos.Length;
                outputParameterCount = outputPos.Length;

                // TODO: Replace with expression to remove performance cost of calling delegate.Invoke.
                InvokeDelegate lambda = delegate(object target, object[] inputs, object[] outputs)
                {
                    object[] paramsLocal = null;
                    if (paramCount > 0)
                    {
                        paramsLocal = new object[paramCount];

                        for (int i = 0; i < inputPos.Length; i++)
                        {
                            paramsLocal[inputPos[i]] = inputs[i];
                        }
                    }

                    object result = null;
                    try
                    {
                        if (returnsValue)
                        {
                            result = method.Invoke(target, paramsLocal);
                        }
                        else
                        {
                            method.Invoke(target, paramsLocal);
                        }
                    }
                    catch (TargetInvocationException tie)
                    {
                        ExceptionDispatchInfo.Capture(tie.InnerException).Throw();
                    }

                    for (int i = 0; i < outputPos.Length; i++)
                    {
                        Debug.Assert(paramsLocal != null);
                        outputs[i] = paramsLocal[outputPos[i]];
                    }

                    return(result);
                };

                return(lambda);
            }
        protected override ServiceDescription CreateDescription(out IDictionary <string, ContractDescription> implementedContracts)
        {
            ServiceDescription description;
            TService           instance = _serviceProvider.GetService <TService>();

            if (instance != null)
            {
                description = ServiceDescription.GetService(instance);
            }
            else
            {
                description = ServiceDescription.GetService <TService>();
            }

            // Any user supplied IServiceBehaviors can be applied now
            var serviceBehaviors = _serviceProvider.GetServices <IServiceBehavior>();

            foreach (var behavior in serviceBehaviors)
            {
                description.Behaviors.Add(behavior);
            }

            ServiceBehaviorAttribute serviceBehavior = description.Behaviors.Find <ServiceBehaviorAttribute>();
            object serviceInstanceUsedAsABehavior    = serviceBehavior.GetWellKnownSingleton();

            if (serviceInstanceUsedAsABehavior == null)
            {
                serviceInstanceUsedAsABehavior = serviceBehavior.GetHiddenSingleton();
                _disposableInstance            = serviceInstanceUsedAsABehavior as IDisposable;
            }

            if ((typeof(IServiceBehavior).IsAssignableFrom(typeof(TService)) || typeof(IContractBehavior).IsAssignableFrom(typeof(TService))) &&
                serviceInstanceUsedAsABehavior == null)
            {
                if (instance == null)
                {
                    serviceInstanceUsedAsABehavior = ServiceDescription.CreateImplementation <TService>();
                }
                else
                {
                    serviceInstanceUsedAsABehavior = instance;
                }

                _disposableInstance = serviceInstanceUsedAsABehavior as IDisposable;
            }

            if (instance != null)
            {
                if (serviceBehavior.InstanceContextMode == InstanceContextMode.Single)
                {
                    SingletonInstance = instance;
                }
                else
                {
                    serviceBehavior.InstanceProvider = new DependencyInjectionInstanceProvider(_serviceProvider, typeof(TService));
                    if (serviceInstanceUsedAsABehavior == null && instance is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }
                }
            }

            if (instance == null)
            {
                if (serviceInstanceUsedAsABehavior is IServiceBehavior)
                {
                    description.Behaviors.Add((IServiceBehavior)serviceInstanceUsedAsABehavior);
                }
            }

            ReflectedContractCollection reflectedContracts = new ReflectedContractCollection();
            List <Type> interfaces = ServiceReflector.GetInterfaces <TService>();

            for (int i = 0; i < interfaces.Count; i++)
            {
                Type contractType = interfaces[i];
                if (!reflectedContracts.Contains(contractType))
                {
                    ContractDescription contract = null;
                    if (serviceInstanceUsedAsABehavior != null)
                    {
                        contract = ContractDescription.GetContract <TService>(contractType, serviceInstanceUsedAsABehavior);
                    }
                    else
                    {
                        contract = ContractDescription.GetContract <TService>(contractType);
                    }

                    reflectedContracts.Add(contract);
                    Collection <ContractDescription> inheritedContracts = contract.GetInheritedContracts();
                    for (int j = 0; j < inheritedContracts.Count; j++)
                    {
                        ContractDescription inheritedContract = inheritedContracts[j];
                        if (!reflectedContracts.Contains(inheritedContract.ContractType))
                        {
                            reflectedContracts.Add(inheritedContract);
                        }
                    }
                }
            }
            ReflectedContracts = reflectedContracts;

            implementedContracts = reflectedContracts.ToImplementedContracts();
            return(description);
        }
        protected override ServiceDescription CreateDescription(out IDictionary <string, ContractDescription> implementedContracts)
        {
            ServiceDescription description;

            if (SingletonInstance != null)
            {
                description = ServiceDescription.GetService(SingletonInstance);
            }
            else
            {
                description = ServiceDescription.GetService <TService>();
            }

            ServiceBehaviorAttribute serviceBehavior = description.Behaviors.Find <ServiceBehaviorAttribute>();
            TService serviceInstanceUsedAsABehavior  = (TService)serviceBehavior.GetWellKnownSingleton();

            if (serviceInstanceUsedAsABehavior == null)
            {
                serviceInstanceUsedAsABehavior = (TService)serviceBehavior.GetHiddenSingleton();
                _disposableInstance            = serviceInstanceUsedAsABehavior as IDisposable;
            }

            if ((typeof(IServiceBehavior).IsAssignableFrom(typeof(TService)) || typeof(IContractBehavior).IsAssignableFrom(typeof(TService))) &&
                serviceInstanceUsedAsABehavior == null)
            {
                serviceInstanceUsedAsABehavior = ServiceDescription.CreateImplementation <TService>();
                _disposableInstance            = serviceInstanceUsedAsABehavior as IDisposable;
            }

            if (SingletonInstance == null)
            {
                if (serviceInstanceUsedAsABehavior is IServiceBehavior)
                {
                    description.Behaviors.Add((IServiceBehavior)serviceInstanceUsedAsABehavior);
                }
            }

            ReflectedContractCollection reflectedContracts = new ReflectedContractCollection();
            List <Type> interfaces = ServiceReflector.GetInterfaces <TService>();

            for (int i = 0; i < interfaces.Count; i++)
            {
                Type contractType = interfaces[i];
                if (!reflectedContracts.Contains(contractType))
                {
                    ContractDescription contract = null;
                    if (serviceInstanceUsedAsABehavior != null)
                    {
                        contract = ContractDescription.GetContract(contractType, serviceInstanceUsedAsABehavior);
                    }
                    else
                    {
                        contract = ContractDescription.GetContract <TService>(contractType);
                    }

                    reflectedContracts.Add(contract);
                    Collection <ContractDescription> inheritedContracts = contract.GetInheritedContracts();
                    for (int j = 0; j < inheritedContracts.Count; j++)
                    {
                        ContractDescription inheritedContract = inheritedContracts[j];
                        if (!reflectedContracts.Contains(inheritedContract.ContractType))
                        {
                            reflectedContracts.Add(inheritedContract);
                        }
                    }
                }
            }
            ReflectedContracts = reflectedContracts;

            implementedContracts = reflectedContracts.ToImplementedContracts();
            return(description);
        }
        protected override ServiceDescription CreateDescription(out IDictionary <string, ContractDescription> implementedContracts)
        {
            ServiceDescription description = _serviceProvider.GetService <ServiceDescription <TService> >();

            ServiceBehaviorAttribute serviceBehavior = description.Behaviors.Find <ServiceBehaviorAttribute>();
            TService serviceInstanceUsedAsABehavior  = (TService)serviceBehavior.GetWellKnownSingleton();

            if (serviceInstanceUsedAsABehavior == null)
            {
                serviceInstanceUsedAsABehavior = (TService)serviceBehavior.GetHiddenSingleton();
                _disposableInstance            = serviceInstanceUsedAsABehavior as IDisposable;
            }

            // serviceInstanceUsedAsBehavior will be null when InstanceContextMode != Single
            // In this case, we need to check if the service type is a behavior and if it is, create an instance to apply to behaviors
            if ((typeof(IServiceBehavior).IsAssignableFrom(typeof(TService)) || typeof(IContractBehavior).IsAssignableFrom(typeof(TService))) &&
                serviceInstanceUsedAsABehavior == null)
            {
                serviceInstanceUsedAsABehavior = _serviceProvider.GetService <TService>(); // First try DI to get an instance
                if (serviceInstanceUsedAsABehavior == null)                                // Not in DI so create the old WCF way using reflection
                {
                    serviceInstanceUsedAsABehavior = ServiceDescription.CreateImplementation <TService>();
                }

                _disposableInstance = serviceInstanceUsedAsABehavior as IDisposable;
            }

            if (serviceBehavior.InstanceContextMode == InstanceContextMode.Single)
            {
                serviceBehavior.ServicePovider = _serviceProvider;

                // If using Single, then ServiceBehavior fetched/created the instance and need to set on SingletonInstance
                Debug.Assert(serviceInstanceUsedAsABehavior != null, "Service behavior should have created a singleton instance");
                SingletonInstance = serviceInstanceUsedAsABehavior;
            }
            else
            {
                serviceBehavior.InstanceProvider = new DependencyInjectionWithLegacyFallbackInstanceProvider(_serviceProvider, typeof(TService));
            }

            if (serviceInstanceUsedAsABehavior is IServiceBehavior behavior)
            {
                description.Behaviors.Add(behavior);
            }

            ReflectedContractCollection reflectedContracts = new ReflectedContractCollection();
            List <Type> interfaces = ServiceReflector.GetInterfaces <TService>();

            for (int i = 0; i < interfaces.Count; i++)
            {
                Type contractType = interfaces[i];
                if (!reflectedContracts.Contains(contractType))
                {
                    ContractDescription contract;
                    if (serviceInstanceUsedAsABehavior != null)
                    {
                        contract = ContractDescription.GetContract <TService>(contractType, serviceInstanceUsedAsABehavior);
                    }
                    else
                    {
                        contract = ContractDescription.GetContract <TService>(contractType);
                    }

                    reflectedContracts.Add(contract);
                    Collection <ContractDescription> inheritedContracts = contract.GetInheritedContracts();
                    for (int j = 0; j < inheritedContracts.Count; j++)
                    {
                        ContractDescription inheritedContract = inheritedContracts[j];
                        if (!reflectedContracts.Contains(inheritedContract.ContractType))
                        {
                            reflectedContracts.Add(inheritedContract);
                        }
                    }
                }
            }
            ReflectedContracts = reflectedContracts;

            implementedContracts = reflectedContracts.ToImplementedContracts();
            return(description);
        }
 private bool NoCoClassAttributeOnType(ICustomAttributeProvider attrProvider)
 {
     return(ServiceReflector.GetCustomAttributes(attrProvider, typeof(CoClassAttribute), false).Length == 0);
 }