protected override void ParseTransformer(XmlElement element, ParserContext parserContext, ObjectDefinitionBuilder builder)
        {
            ManagedDictionary      headers    = new ManagedDictionary();
            XmlAttributeCollection attributes = element.Attributes;

            for (int i = 0; i < attributes.Count; i++)
            {
                XmlNode node = attributes.Item(i);
                String  name = node.LocalName;
                if (IsEligibleHeaderName(name))
                {
                    name = Conventions.AttributeNameToPropertyName(name);
                    object value;
                    if (ReferenceAttributesContains(name))
                    {
                        value = new RuntimeObjectReference(node.Value);
                    }
                    else
                    {
                        value = node.Value;
                    }

                    if (_prefix != null)
                    {
                        name = _prefix + name;
                    }
                    headers.Add(name, value);
                }
            }
            PostProcessHeaders(element, headers, parserContext);
            builder.AddConstructorArg(headers);
            builder.AddPropertyValue("overwrite", ShouldOverwrite(element));
        }
        /// <summary>
        /// Creates and initialise the object definition that will be registered in your context.
        /// </summary>
        /// <param name="objectDefinitionService">The object definition service.</param>
        /// <returns></returns>
        public IObjectDefinition GetObjectDefinition(IObjectDefinitionService objectDefinitionService)
        {
            if (_interfaceType == null || String.IsNullOrEmpty(_interfaceType.FullName))
            {
                throw new ConfigurationErrorsException(string.Format("You are trying to bind a type to a null interface!"));
            }

            IConfigurableObjectDefinition objectDefinition;
            var conditionalList = new ManagedList();

            if (!objectDefinitionService.Registry.ContainsObjectDefinition(_interfaceType.FullName))
            {
                objectDefinition            = objectDefinitionService.Factory.CreateObjectDefinition(typeof(ConstrainableDuringLoadFactoryObject).AssemblyQualifiedName, null, AppDomain.CurrentDomain);
                objectDefinition.ObjectType = typeof(ConstrainableDuringLoadFactoryObject);
                objectDefinition.PropertyValues.Add("IsSingleton", _isStatic);
                objectDefinition.PropertyValues.Add("ConditionObjectDefinitions", conditionalList);
            }
            else
            {
                objectDefinition = (IConfigurableObjectDefinition)objectDefinitionService.Registry.GetObjectDefinition(_interfaceType.FullName);
                conditionalList  = (ManagedList)objectDefinition.PropertyValues.GetPropertyValue("ConditionObjectDefinitions").Value;
            }

            if (_constraintRegistry.ContainsKey(_interfaceType.FullName))
            {
                foreach (ConditionalObjectDefinition conditionalDefinition in _constraintRegistry[_interfaceType.FullName])
                {
                    IConfigurableObjectDefinition definition = objectDefinitionService.Factory.CreateObjectDefinition(typeof(ConditionalObjectDefinition).AssemblyQualifiedName, null, AppDomain.CurrentDomain);
                    definition.ConstructorArgumentValues.AddIndexedArgumentValue(0, conditionalDefinition.Condition);
                    definition.ConstructorArgumentValues.AddIndexedArgumentValue(1, conditionalDefinition.TypeName);
                    definition.ConstructorArgumentValues.AddIndexedArgumentValue(2, conditionalDefinition.IsDefault);

                    var ro = new RuntimeObjectReference(conditionalDefinition.TypeName);
                    definition.PropertyValues.Add("Instance", ro);

                    conditionalList.Add(definition);
                }
            }

            return(objectDefinition);
        }
コード例 #3
0
        /// <summary>
        /// Resolve a reference to another object in the factory.
        /// </summary>
        /// <param name="name">
        /// The name of the object that is having the value of one of its properties resolved.
        /// </param>
        /// <param name="definition">
        /// The definition of the named object.
        /// </param>
        /// <param name="argumentName">
        /// The name of the property the value of which is being resolved.
        /// </param>
        /// <param name="reference">
        /// The runtime reference containing the value of the property.
        /// </param>
        /// <returns>A reference to another object in the factory.</returns>
        protected virtual object ResolveReference(IObjectDefinition definition, string name, string argumentName, RuntimeObjectReference reference)
        {
            #region Instrumentation
            if (log.IsDebugEnabled)
            {
                log.Debug(
                    string.Format(CultureInfo.InvariantCulture, "Resolving reference from property '{0}' in object '{1}' to object '{2}'.",
                                  argumentName, name, reference.ObjectName));
            }
            #endregion

            try
            {
                if (reference.IsToParent)
                {
                    if (null == objectFactory.ParentObjectFactory)
                    {
                        throw new ObjectCreationException(definition.ResourceDescription, name,
                                                          string.Format(
                                                              "Can't resolve reference to '{0}' in parent factory: " + "no parent factory available.",
                                                              reference.ObjectName));
                    }
                    return(objectFactory.ParentObjectFactory.GetObject(reference.ObjectName));
                }
                return(objectFactory.GetObject(reference.ObjectName));
            }
            catch (ObjectsException ex)
            {
                throw ObjectCreationException.GetObjectCreationException(ex, name, argumentName, definition.ResourceDescription, reference.ObjectName);
            }
        }
コード例 #4
0
        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="name">
        /// The name of the object that is having the value of one of its properties resolved.
        /// </param>
        /// <param name="definition">
        /// The definition of the named object.
        /// </param>
        /// <param name="argumentName">
        /// The name of the property the value of which is being resolved.
        /// </param>
        /// <param name="argumentValue">
        /// The value of the property that is being resolved.
        /// </param>
        private object ResolvePropertyValue(string name, IObjectDefinition definition, string argumentName, object argumentValue)
        {
            object resolvedValue = null;

            // we must check the argument value to see whether it requires a runtime
            // reference to another object to be resolved.
            // if it does, we'll attempt to instantiate the object and set the reference.
            if (RemotingServices.IsTransparentProxy(argumentValue))
            {
                resolvedValue = argumentValue;
            }
            else if (argumentValue is ICustomValueReferenceHolder)
            {
                resolvedValue = ((ICustomValueReferenceHolder)argumentValue).Resolve(objectFactory, name, definition, argumentName, argumentValue);
            }
            else if (argumentValue is ObjectDefinitionHolder)
            {
                // contains an IObjectDefinition with name and aliases...
                ObjectDefinitionHolder holder = (ObjectDefinitionHolder)argumentValue;
                resolvedValue = ResolveInnerObjectDefinition(name, holder.ObjectName, argumentName, holder.ObjectDefinition, definition.IsSingleton);
            }
            else if (argumentValue is IObjectDefinition)
            {
                // resolve plain IObjectDefinition, without contained name: use dummy name...
                IObjectDefinition def = (IObjectDefinition)argumentValue;
                resolvedValue = ResolveInnerObjectDefinition(name, "(inner object)", argumentName, def, definition.IsSingleton);
            }
            else if (argumentValue is RuntimeObjectReference)
            {
                RuntimeObjectReference roref = (RuntimeObjectReference)argumentValue;
                resolvedValue = ResolveReference(definition, name, argumentName, roref);
            }
            else if (argumentValue is ExpressionHolder)
            {
                ExpressionHolder             expHolder = (ExpressionHolder)argumentValue;
                object                       context   = null;
                IDictionary <string, object> variables = null;

                if (expHolder.Properties != null)
                {
                    PropertyValue contextProperty = expHolder.Properties.GetPropertyValue("Context");
                    context = contextProperty == null
                                  ? null
                                  : ResolveValueIfNecessary(name, definition, "Context",
                                                            contextProperty.Value);
                    PropertyValue variablesProperty = expHolder.Properties.GetPropertyValue("Variables");
                    object        vars = (variablesProperty == null
                                       ? null
                                       : ResolveValueIfNecessary(name, definition, "Variables",
                                                                 variablesProperty.Value));
                    if (vars is IDictionary <string, object> )
                    {
                        variables = (IDictionary <string, object>)vars;
                    }
                    if (vars is IDictionary)
                    {
                        IDictionary temp = (IDictionary)vars;
                        variables = new Dictionary <string, object>(temp.Count);
                        foreach (DictionaryEntry entry in temp)
                        {
                            variables.Add((string)entry.Key, entry.Value);
                        }
                    }
                    else
                    {
                        if (vars != null)
                        {
                            throw new ArgumentException("'Variables' must resolve to an IDictionary");
                        }
                    }
                }

                if (variables == null)
                {
                    variables = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
                }
                // add 'this' objectfactory reference to variables
                variables.Add(Expression.ReservedVariableNames.CurrentObjectFactory, objectFactory);

                resolvedValue = expHolder.Expression.GetValue(context, variables);
            }
            else if (argumentValue is IManagedCollection)
            {
                resolvedValue =
                    ((IManagedCollection)argumentValue).Resolve(name, definition, argumentName, ResolveValueIfNecessary);
            }
            else if (argumentValue is TypedStringValue)
            {
                TypedStringValue tsv = (TypedStringValue)argumentValue;
                try
                {
                    Type resolvedTargetType = ResolveTargetType(tsv);
                    if (resolvedTargetType != null)
                    {
                        resolvedValue = TypeConversionUtils.ConvertValueIfNecessary(tsv.TargetType, tsv.Value, null);
                    }
                    else
                    {
                        resolvedValue = tsv.Value;
                    }
                }
                catch (Exception ex)
                {
                    throw new ObjectCreationException(definition.ResourceDescription, name,
                                                      "Error converted typed String value for " + argumentName, ex);
                }
            }
            else
            {
                // no need to resolve value...
                resolvedValue = argumentValue;
            }
            return(resolvedValue);
        }
コード例 #5
0
            public override void Inject(Object target, string objectName, IPropertyValues pvs)
            {
                MethodInfo method = _member as MethodInfo;

                try
                {
                    Object[] arguments;
                    if (_cached)
                    {
                        arguments = ResolveCachedArguments(objectName);
                    }
                    else
                    {
                        Type[] paramTypes = method.GetParameters().Select(p => p.ParameterType).ToArray();
                        arguments = new Object[paramTypes.Length];
                        var   descriptors        = new DependencyDescriptor[paramTypes.Length];
                        IList autowiredBeanNames = new ArrayList();
                        for (int i = 0; i < arguments.Length; i++)
                        {
                            MethodParameter methodParam = new MethodParameter(method, i);
                            descriptors[i] = new DependencyDescriptor(methodParam, _required);
                            arguments[i]   = _objectFactory.ResolveDependency(descriptors[i], objectName,
                                                                              autowiredBeanNames);
                            if (arguments[i] == null && !_required)
                            {
                                arguments = null;
                                break;
                            }
                        }
                        lock (this)
                        {
                            if (!_cached)
                            {
                                if (arguments != null)
                                {
                                    _cachedMethodArguments = new Object[arguments.Length];
                                    for (int i = 0; i < arguments.Length; i++)
                                    {
                                        _cachedMethodArguments[i] = descriptors[i];
                                    }
                                    RegisterDependentObjects(objectName, autowiredBeanNames);
                                    if (autowiredBeanNames.Count == paramTypes.Length)
                                    {
                                        for (int i = 0; i < paramTypes.Length; i++)
                                        {
                                            string autowiredBeanName = autowiredBeanNames[i] as string;
                                            if (_objectFactory.ContainsObject(autowiredBeanName))
                                            {
                                                if (_objectFactory.IsTypeMatch(autowiredBeanName, paramTypes[i]))
                                                {
                                                    _cachedMethodArguments[i] =
                                                        new RuntimeObjectReference(autowiredBeanName);
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    _cachedMethodArguments = null;
                                }
                                _cached = true;
                            }
                        }
                    }
                    if (arguments != null)
                    {
                        method.Invoke(target, arguments);
                    }
                }
                catch (Exception ex)
                {
                    throw new ObjectCreationException("Could not autowire method: " + method, ex);
                }
            }
コード例 #6
0
        /// <summary>
        /// Get all property values, given a prefix (which will be stripped)
        /// and add the object they define to the factory with the given name
        /// </summary>
        /// <param name="name">The name of the object to define.</param>
        /// <param name="id">
        /// The <see cref="System.Collections.IDictionary"/> containing string pairs.
        /// </param>
        /// <param name="prefix">The prefix of each entry, which will be stripped.</param>
        /// <param name="resourceDescription">
        /// The description of the resource that the
        /// <see cref="System.Collections.IDictionary"/> came from (for logging purposes).
        /// </param>
        /// <exception cref="Oragon.Spring.Objects.ObjectsException">
        /// In case of loading or parsing errors.
        /// </exception>
        protected void RegisterObjectDefinition(
            string name, IDictionary id, string prefix, string resourceDescription)
        {
            string typeName  = null;
            string parent    = null;
            bool   singleton = true;
            bool   lazyInit  = false;

            MutablePropertyValues pvs = new MutablePropertyValues();

            foreach (string key in id.Keys)
            {
                if (key.StartsWith(prefix + Separator))
                {
                    string property = key.Substring(prefix.Length + Separator.Length);
                    if (property.Equals(ClassKey))
                    {
                        typeName = (string)id[key];
                    }
                    else if (property.Equals(SingletonKey))
                    {
                        string val = (string)id[key];
                        singleton = (val == null) || val.Equals(TrueValue);
                    }
                    else if (property.Equals(LazyInitKey))
                    {
                        string val = (string)id[key];
                        lazyInit = val.Equals(TrueValue);
                    }
                    else if (property.Equals(ParentKey))
                    {
                        parent = (string)id[key];
                    }
                    else if (property.EndsWith(RefSuffix))
                    {
                        // This isn't a real property, but a reference to another prototype
                        // Extract property name: property is of form dog(ref)
                        property = property.Substring(0, property.Length - RefSuffix.Length);
                        string reference = (String)id[key];

                        // It doesn't matter if the referenced object hasn't yet been registered:
                        // this will ensure that the reference is resolved at runtime
                        // Default is not to use singleton
                        object val = new RuntimeObjectReference(reference);
                        pvs.Add(new PropertyValue(property, val));
                    }
                    else
                    {
                        // normal object property
                        object val = id[key];
                        if (val is String)
                        {
                            string strVal = (string)val;
                            // if it starts with a reference prefix...
                            if (strVal.StartsWith(RefPrefix))
                            {
                                // expand reference
                                string targetName = strVal.Substring(1);
                                if (targetName.StartsWith(RefPrefix))
                                {
                                    // escaped prefix -> use plain value
                                    val = targetName;
                                }
                                else
                                {
                                    val = new RuntimeObjectReference(targetName);
                                }
                            }
                        }
                        pvs.Add(new PropertyValue(property, val));
                    }
                }
            }
            if (log.IsDebugEnabled)
            {
                log.Debug(pvs.ToString());
            }
            if (parent == null)
            {
                log.Debug(this.DefaultParentObject);
                parent = this.DefaultParentObject;
            }
            if (typeName == null && parent == null)
            {
                throw new ObjectDefinitionStoreException(resourceDescription, name,
                                                         "Either 'type' or 'parent' is required");
            }
            try
            {
                IConfigurableObjectDefinition objectDefinition = ObjectDefinitionFactory.CreateObjectDefinition(typeName, parent, Domain);
                objectDefinition.PropertyValues = pvs;
                objectDefinition.IsSingleton    = singleton;
                objectDefinition.IsLazyInit     = lazyInit;
                Registry.RegisterObjectDefinition(name, objectDefinition);
            }
            catch (Exception ex)
            {
                throw new ObjectDefinitionStoreException(
                          resourceDescription, name, "Unable to load type [" + typeName + "]", ex);
            }
        }
コード例 #7
0
 public void Add <T>(Func <IObjectDefinitionService, object> keyObjectReference, RuntimeObjectReference actualValue)
 {
     _managedDictionaryAction.Add((d, f) => d.Add(keyObjectReference(f), actualValue));
 }
コード例 #8
0
 public void Add(RuntimeObjectReference keyObjectReference, Func <IObjectDefinitionService, object> runtimeObjectReference)
 {
     _managedDictionaryAction.Add((d, f) => d.Add(keyObjectReference, runtimeObjectReference(f)));
 }
コード例 #9
0
 public void Add <V>(RuntimeObjectReference keyObjectReference, V actualValue)
 {
     _managedDictionaryAction.Add((d, f) => d.Add(keyObjectReference, actualValue));
 }
コード例 #10
0
 public void Add <T>(T keyValue, RuntimeObjectReference runtimeObjectReference)
 {
     _managedDictionaryAction.Add((d, f) => d.Add(keyValue, runtimeObjectReference));
 }
コード例 #11
0
 public void Add(RuntimeObjectReference keyObjectReference, RuntimeObjectReference valueObjectReference)
 {
     _managedDictionaryAction.Add((d, f) => d.Add(keyObjectReference, valueObjectReference));
 }
 public void AddInjectedTypeIdentifierName(Type injectedPropertyType, string injectedIdentifierName)
 {
     _typeInjections[injectedPropertyType] = new RuntimeObjectReference(injectedIdentifierName);
 }
コード例 #13
0
        /// <summary>The parse map element.</summary>
        /// <param name="mapEle">The map ele.</param>
        /// <param name="bd">The bd.</param>
        /// <returns>The System.Collections.IDictionary.</returns>
        public IDictionary ParseMapElement(XmlElement mapEle, IObjectDefinition bd)
        {
            string defaultKeyType   = mapEle.GetAttribute(KEY_TYPE_ATTRIBUTE);
            string defaultValueType = mapEle.GetAttribute(VALUE_TYPE_ATTRIBUTE);

            XmlNodeList entryEles = mapEle.GetElementsByTagName(ENTRY_ELEMENT, OBJECTS_NAMESPACE_URI);
            var         map       = new ManagedDictionary(entryEles.Count);

            map.KeyTypeName   = defaultKeyType;
            map.ValueTypeName = defaultValueType;
            map.MergeEnabled  = this.ParseMergeAttribute(mapEle);

            foreach (XmlNode entryEle in entryEles)
            {
                // Should only have one value child element: ref, value, list, etc.
                // Optionally, there might be a key child element.
                XmlNodeList entrySubNodes = entryEle.ChildNodes;
                XmlElement  keyEle        = null;
                XmlElement  valueEle      = null;
                for (int j = 0; j < entrySubNodes.Count; j++)
                {
                    XmlNode node = entrySubNodes.Item(j);
                    if (node is XmlElement)
                    {
                        var candidateEle = (XmlElement)node;
                        if (this.NodeNameEquals(candidateEle, KEY_ELEMENT))
                        {
                            if (keyEle != null)
                            {
                                this.Error("<entry> element is only allowed to contain one <key> sub-element", entryEle);
                            }
                            else
                            {
                                keyEle = candidateEle;
                            }
                        }
                        else
                        {
                            // Child element is what we're looking for.
                            if (valueEle != null)
                            {
                                this.Error("<entry> element must not contain more than one value sub-element", entryEle);
                            }
                            else
                            {
                                valueEle = candidateEle;
                            }
                        }
                    }
                }

                // Extract key from attribute or sub-element.
                object key                = null;
                bool   hasKeyAttribute    = this.HasAttribute(entryEle, KEY_ATTRIBUTE);
                bool   hasKeyRefAttribute = this.HasAttribute(entryEle, KEY_REF_ATTRIBUTE);
                if ((hasKeyAttribute && hasKeyRefAttribute) ||
                    (hasKeyAttribute || hasKeyRefAttribute) && keyEle != null)
                {
                    this.Error(
                        "<entry> element is only allowed to contain either " +
                        "a 'key' attribute OR a 'key-ref' attribute OR a <key> sub-element",
                        entryEle);
                }

                if (hasKeyAttribute)
                {
                    key = this.buildTypedStringValueForMap(entryEle.Attributes[KEY_ATTRIBUTE].Value, defaultKeyType);
                }
                else if (hasKeyRefAttribute)
                {
                    string refName = entryEle.Attributes[KEY_REF_ATTRIBUTE].Value;
                    if (!StringUtils.HasText(refName))
                    {
                        this.Error("<entry> element contains empty 'key-ref' attribute", entryEle);
                    }

                    var reference = new RuntimeObjectReference(refName);
                    key = reference;
                }
                else if (keyEle != null)
                {
                    key = this.parseKeyElement(keyEle, bd, defaultKeyType);
                }
                else
                {
                    this.Error("<entry> element must specify a key", entryEle);
                }

                // Extract value from attribute or sub-element.
                object value                = null;
                bool   hasValueAttribute    = this.HasAttribute(entryEle, VALUE_ATTRIBUTE);
                bool   hasValueRefAttribute = this.HasAttribute(entryEle, VALUE_REF_ATTRIBUTE);
                if ((hasValueAttribute && hasValueRefAttribute) ||
                    (hasValueAttribute || hasValueRefAttribute) && valueEle != null)
                {
                    this.Error(
                        "<entry> element is only allowed to contain either " +
                        "'value' attribute OR 'value-ref' attribute OR <value> sub-element",
                        entryEle);
                }

                if (hasValueAttribute)
                {
                    value = this.buildTypedStringValueForMap(entryEle.Attributes[VALUE_ATTRIBUTE].Value, defaultValueType);
                }
                else if (hasValueRefAttribute)
                {
                    string refName = entryEle.Attributes[VALUE_REF_ATTRIBUTE].Value;
                    if (!StringUtils.HasText(refName))
                    {
                        this.Error("<entry> element contains empty 'value-ref' attribute", entryEle);
                    }

                    var reference = new RuntimeObjectReference(refName);
                    value = reference;
                }
                else if (valueEle != null)
                {
                    value = this.parsePropertySubElement(valueEle, bd, defaultValueType);
                }
                else
                {
                    this.Error("<entry> element must specify a value", entryEle);
                }

                // Add final key and value to the Map.
                map.Add(key, value);
            }

            return(map);
        }
コード例 #14
0
        private object parsePropertySubElement(XmlElement ele, IObjectDefinition bd, string defaultValueType)
        {
            if (!isDefaultNamespace(ele))
            {
                return(this.parseNestedCustomElement(ele, bd));
            }
            else if (this.NodeNameEquals(ele, OBJECT_ELEMENT))
            {
                ObjectDefinitionHolder nestedBd = this.parserContext.ParserHelper.ParseObjectDefinitionElement(ele, bd);

                // if (nestedBd != null)
                // {
                // nestedBd = decorateObjectDefinitionIfRequired(ele, nestedBd, bd);
                // }
                return(nestedBd);
            }
            else if (this.NodeNameEquals(ele, REF_ELEMENT))
            {
                // A generic reference to any name of any object.
                string refName  = ele.GetAttribute(OBJECT_REF_ATTRIBUTE);
                bool   toParent = false;
                if (!StringUtils.HasLength(refName))
                {
                    // A reference to the id of another object in the same XML file.
                    refName = ele.GetAttribute(LOCAL_REF_ATTRIBUTE);
                    if (!StringUtils.HasLength(refName))
                    {
                        // A reference to the id of another object in a parent context.
                        refName  = ele.GetAttribute(PARENT_REF_ATTRIBUTE);
                        toParent = true;
                        if (!StringUtils.HasLength(refName))
                        {
                            this.Error("'object', 'local' or 'parent' is required for <ref> element", ele);
                            return(null);
                        }
                    }
                }

                if (!StringUtils.HasText(refName))
                {
                    this.Error("<ref> element contains empty target attribute", ele);
                    return(null);
                }

                var reference = new RuntimeObjectReference(refName, toParent);
                return(reference);
            }


            // else if (NodeNameEquals(ele, IDREF_ELEMENT)) {
            // return parseIdRefElement(ele);
            // }
            else if (this.NodeNameEquals(ele, VALUE_ELEMENT))
            {
                return(this.parseValueElement(ele, defaultValueType));
            }
            else if (this.NodeNameEquals(ele, NULL_ELEMENT))
            {
                // It's a distinguished null value. Let's wrap it in a TypedStringValue
                // object in order to preserve the source location.
                var nullHolder = new TypedStringValue(null);
                return(nullHolder);
            }
            else if (this.NodeNameEquals(ele, ARRAY_ELEMENT))
            {
                return(this.parseArrayElement(ele, bd));
            }
            else if (this.NodeNameEquals(ele, LIST_ELEMENT))
            {
                return(this.parseListElement(ele, bd));
            }
            else if (this.NodeNameEquals(ele, SET_ELEMENT))
            {
                return(this.parseSetElement(ele, bd));
            }
            else if (this.NodeNameEquals(ele, MAP_ELEMENT))
            {
                return(this.ParseMapElement(ele, bd));
            }



            // else if (NodeNameEquals(ele, PROPS_ELEMENT))
            // {
            // return parsePropsElement(ele);
            // }
            else
            {
                this.Error("Unknown property sub-element: [" + ele.Name + "]", ele);
                return(null);
            }
        }