public void InstantiationIsImplictlyNotToParent()
		{
			RuntimeObjectReference ror = new RuntimeObjectReference("foo");
			Assert.IsFalse(ror.IsToParent,
				"IsToParent property must default to false if not " +
				"using the explicit variant of the ctor.");
        }
        public void InstantiationIsImplictlyNotToParent()
		{
			RuntimeObjectReference ror = new RuntimeObjectReference("foo");
			Assert.IsFalse(ror.IsToParent,
				"IsToParent property must default to false if not " +
				"using the explicit variant of the ctor.");
        }
Exemplo n.º 3
0
 /// <summary>
 /// Resolves the given value taken from an object definition according to its type
 /// </summary>
 /// <param name="value">the value to resolve</param>
 /// <returns>the resolved value</returns>
 protected virtual object ResolveValue(object value)
 {
     if (value is IObjectDefinition)
     {
         VisitObjectDefinition((IObjectDefinition)value);
     }
     else if (value is ObjectDefinitionHolder)
     {
         VisitObjectDefinition(((ObjectDefinitionHolder)value).ObjectDefinition);
     }
     else if (value is RuntimeObjectReference)
     {
         RuntimeObjectReference ror = (RuntimeObjectReference)value;
         //name has to be of string type.
         string newObjectName = ResolveStringValue(ror.ObjectName);
         if (!newObjectName.Equals(ror.ObjectName))
         {
             return(new RuntimeObjectReference(newObjectName));
         }
     }
     else if (value is ManagedList)
     {
         VisitManagedList((ManagedList)value);
     }
     else if (value is ManagedSet)
     {
         VisitManagedSet((ManagedSet)value);
     }
     else if (value is ManagedDictionary)
     {
         VisitManagedDictionary((ManagedDictionary)value);
     }
     else if (value is NameValueCollection)
     {
         VisitNameValueCollection((NameValueCollection)value);
     }
     else if (value is TypedStringValue)
     {
         TypedStringValue typedStringValue = (TypedStringValue)value;
         String           stringValue      = typedStringValue.Value;
         if (stringValue != null)
         {
             String visitedString = ResolveStringValue(stringValue);
             typedStringValue.Value = visitedString;
         }
     }
     else if (value is string)
     {
         return(ResolveStringValue((string)value));
     }
     else if (value is ExpressionHolder)
     {
         ExpressionHolder holder = (ExpressionHolder)value;
         string           newExpressionString = ResolveStringValue(holder.ExpressionString);
         return(new ExpressionHolder(newExpressionString));
     }
     return(value);
 }
 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);
     }
 }
        /// <summary>Parses an event listener definition.</summary>
        /// <param name="name">
        /// The name associated with the object that the event handler is being defined on.
        /// </param>
        /// <param name="events">The events being populated.</param>
        /// <param name="element">
        /// The element containing the event listener definition.
        /// </param>
        /// <param name="parserContext">
        /// The namespace-aware parser.
        /// </param>
        protected virtual void ParseEventListenerDefinition(
            string name, EventValues events, XmlElement element, ParserContext parserContext)
        {
            // get an appropriate IEventHandlerValue instance based upon the
            // attribute values of the listener element...
            IEventHandlerValue myHandler = ObjectDefinitionReaderUtils.CreateEventHandlerValue(
                GetAttributeValue(element, ObjectDefinitionConstants.ListenerMethodAttribute),
                GetAttributeValue(element, ObjectDefinitionConstants.ListenerEventAttribute));

            // and then get the source of the event (another managed object instance
            // or a Type reference (i.e. a static event exposed on a class)...
            XmlElement sourceElement = this.SelectSingleNode(element, ObjectDefinitionConstants.RefElement) as XmlElement;

            XmlAttribute sourceAtt = sourceElement.Attributes[0];
            if (StringUtils.IsNullOrEmpty(sourceAtt.Value))
            {
                parserContext.ReaderContext.ReportFatalException(sourceElement, string.Format(
                    CultureInfo.InvariantCulture,
                    "The single attribute of the <{0}/> element cannot be empty. Specify the " +
                        "object id (alias) or the full, assembly qualified Type name that is the " +
                        "source of the event.",
                    ObjectDefinitionConstants.RefElement));
                return;
            }
            switch (sourceAtt.LocalName)
            {
                case ObjectDefinitionConstants.LocalRefAttribute:
                case ObjectDefinitionConstants.ObjectRefAttribute:
                    // we're wiring up to an event exposed on another managed object (instance)
                    RuntimeObjectReference ror = new RuntimeObjectReference(sourceAtt.Value);
                    myHandler.Source = ror;
                    break;
                case ObjectDefinitionConstants.TypeAttribute:
                    // we're wiring up to a static event exposed on a Type (class)
                    myHandler.Source = parserContext.ReaderContext.Reader.Domain == null ?
                        (object)sourceAtt.Value :
                        (object)TypeResolutionUtils.ResolveType(sourceAtt.Value);
                    break;
            }
            events.AddHandler(myHandler);
        }
        /// <summary>
        /// Gets a dictionary definition.
        /// </summary>
        /// <param name="mapEle">The element describing the dictionary definition.</param>
        /// <param name="name">The name of the object (definition) associated with the dictionary definition.</param>
        /// <param name="parserContext">The namespace-aware parser.</param>
        /// <returns>The dictionary definition.</returns>
        protected IDictionary ParseDictionaryElement(XmlElement mapEle, string name, ParserContext parserContext)
        {
            ManagedDictionary dictionary = new ManagedDictionary();
            string keyTypeName = GetAttributeValue(mapEle, "key-type");
            string valueTypeName = GetAttributeValue(mapEle, "value-type");
            if (StringUtils.HasText(keyTypeName))
            {
                dictionary.KeyTypeName = keyTypeName;
            }
            if (StringUtils.HasText(valueTypeName))
            {
                dictionary.ValueTypeName = valueTypeName;
            }
            dictionary.MergeEnabled = ParseMergeAttribute(mapEle, parserContext.ParserHelper);

            XmlNodeList entryElements = SelectNodes(mapEle, ObjectDefinitionConstants.EntryElement);
            foreach (XmlElement entryEle in entryElements)
            {
                #region Key

                object key = null;

                XmlAttribute keyAtt = entryEle.Attributes[ObjectDefinitionConstants.KeyAttribute];
                if (keyAtt != null)
                {
                    key = keyAtt.Value;
                }
                else
                {
                    // ok, we're not using the 'key' attribute; lets check for the ref shortcut...
                    XmlAttribute keyRefAtt = entryEle.Attributes[ObjectDefinitionConstants.DictionaryKeyRefShortcutAttribute];
                    if (keyRefAtt != null)
                    {
                        key = new RuntimeObjectReference(keyRefAtt.Value);
                    }
                    else
                    {
                        // so check for the 'key' element...
                        XmlNode keyNode = SelectSingleNode(entryEle, ObjectDefinitionConstants.KeyElement);
                        if (keyNode == null)
                        {
                            throw new ObjectDefinitionStoreException(
                                parserContext.ReaderContext.Resource, name,
                                string.Format("One of either the '{0}' element, or the the '{1}' or '{2}' attributes " +
                                              "is required for the <{3}/> element.",
                                              ObjectDefinitionConstants.KeyElement,
                                              ObjectDefinitionConstants.KeyAttribute,
                                              ObjectDefinitionConstants.DictionaryKeyRefShortcutAttribute,
                                              ObjectDefinitionConstants.EntryElement));
                        }
                        XmlElement keyElement = (XmlElement)keyNode;
                        XmlNodeList keyNodes = keyElement.GetElementsByTagName("*");
                        if (keyNodes == null || keyNodes.Count == 0)
                        {
                            throw new ObjectDefinitionStoreException(
                                parserContext.ReaderContext.Resource, name,
                                string.Format("Malformed <{0}/> element... the value of the key must be " +
                                    "specified as a child value-style element.",
                                              ObjectDefinitionConstants.KeyElement));
                        }
                        key = ParsePropertySubElement((XmlElement)keyNodes.Item(0), name, parserContext);
                    }
                }

                #endregion

                #region Value

                XmlAttribute inlineValueAtt = entryEle.Attributes[ObjectDefinitionConstants.ValueAttribute];
                if (inlineValueAtt != null)
                {
                    // ok, we're using the value attribute shortcut...
                    dictionary[key] = inlineValueAtt.Value;
                }
                else if (entryEle.Attributes[ObjectDefinitionConstants.DictionaryValueRefShortcutAttribute] != null)
                {
                    // ok, we're using the value-ref attribute shortcut...
                    XmlAttribute inlineValueRefAtt = entryEle.Attributes[ObjectDefinitionConstants.DictionaryValueRefShortcutAttribute];
                    RuntimeObjectReference ror = new RuntimeObjectReference(inlineValueRefAtt.Value);
                    dictionary[key] = ror;
                }
                else if (entryEle.Attributes[ObjectDefinitionConstants.ExpressionAttribute] != null)
                {
                    // ok, we're using the expression attribute shortcut...
                    XmlAttribute inlineExpressionAtt = entryEle.Attributes[ObjectDefinitionConstants.ExpressionAttribute];
                    ExpressionHolder expHolder = new ExpressionHolder(inlineExpressionAtt.Value);
                    dictionary[key] = expHolder;
                }
                else
                {
                    XmlNode keyNode = SelectSingleNode(entryEle, ObjectDefinitionConstants.KeyElement);
                    if (keyNode != null)
                    {
                        entryEle.RemoveChild(keyNode);
                    }
                    // ok, we're using the original full-on value element...
                    XmlNodeList valueElements = entryEle.GetElementsByTagName("*");
                    if (valueElements == null || valueElements.Count == 0)
                    {
                        throw new ObjectDefinitionStoreException(
                            parserContext.ReaderContext.Resource, name,
                            string.Format("One of either the '{0}' or '{1}' attributes, or a value-style element " +
                                "is required for the <{2}/> element.",
                                          ObjectDefinitionConstants.ValueAttribute, ObjectDefinitionConstants.DictionaryValueRefShortcutAttribute, ObjectDefinitionConstants.EntryElement));
                    }
                    dictionary[key] = ParsePropertySubElement((XmlElement)valueElements.Item(0), name, parserContext);
                }

                #endregion
            }
            return dictionary;
        }
        /// <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="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);
            }
        }
 protected override void VisitResolvedParameterValue(ContainerResolvedParameter parameterValue)
 {
    string name = parameterValue.Name ?? String.Format("{0}.{1}", parameterValue.Type.Name, "__default__");          
    InjectionParameter = new RuntimeObjectReference(String.Concat(name,".", parameterValue.Type.Name));
 }
        public void SunnyDay()
        {
            StaticApplicationContext ac = new StaticApplicationContext();


            MutablePropertyValues pvs = new MutablePropertyValues();

            pvs.Add("age", "${age}");
            RootObjectDefinition def
                = new RootObjectDefinition("${fqn}", new ConstructorArgumentValues(), pvs);

            ac.RegisterObjectDefinition("tb3", def);



            pvs = new MutablePropertyValues();
            pvs.Add("age", "${age}");
            pvs.Add("name", "name${var}${");
            pvs.Add("spouse", new RuntimeObjectReference("${ref}"));
            ac.RegisterSingleton("tb1", typeof(TestObject), pvs);

            ConstructorArgumentValues cas = new ConstructorArgumentValues();

            cas.AddIndexedArgumentValue(1, "${age}");
            cas.AddGenericArgumentValue("${var}name${age}");

            pvs = new MutablePropertyValues();
            ArrayList friends = new ManagedList();

            friends.Add("na${age}me");
            friends.Add(new RuntimeObjectReference("${ref}"));
            pvs.Add("friends", friends);

            ISet someSet = new ManagedSet();

            someSet.Add("na${age}me");
            someSet.Add(new RuntimeObjectReference("${ref}"));
            pvs.Add("someSet", someSet);

            IDictionary someDictionary = new ManagedDictionary();

            someDictionary["key1"] = new RuntimeObjectReference("${ref}");
            someDictionary["key2"] = "${age}name";
            MutablePropertyValues innerPvs = new MutablePropertyValues();

            someDictionary["key3"] = new RootObjectDefinition(typeof(TestObject), innerPvs);
            someDictionary["key4"] = new ChildObjectDefinition("tb1", innerPvs);
            pvs.Add("someMap", someDictionary);

            RootObjectDefinition definition = new RootObjectDefinition(typeof(TestObject), cas, pvs);

            ac.DefaultListableObjectFactory.RegisterObjectDefinition("tb2", definition);

            pvs = new MutablePropertyValues();
            pvs.Add("Properties", "<spring-config><add key=\"age\" value=\"98\"/><add key=\"var\" value=\"${m}var\"/><add key=\"ref\" value=\"tb2\"/><add key=\"m\" value=\"my\"/><add key=\"fqn\" value=\"Spring.Objects.TestObject, Spring.Core.Tests\"/></spring-config>");
            ac.RegisterSingleton("configurer", typeof(PropertyPlaceholderConfigurer), pvs);
            ac.Refresh();

            TestObject tb1 = (TestObject)ac.GetObject("tb1");
            TestObject tb2 = (TestObject)ac.GetObject("tb2");
            TestObject tb3 = (TestObject)ac.GetObject("tb3");

            Assert.AreEqual(98, tb1.Age);
            Assert.AreEqual(98, tb2.Age);
            Assert.AreEqual(98, tb3.Age);
            Assert.AreEqual("namemyvar${", tb1.Name);
            Assert.AreEqual("myvarname98", tb2.Name);
            Assert.AreEqual(tb2, tb1.Spouse);
            Assert.AreEqual(2, tb2.Friends.Count);
            IEnumerator ie = tb2.Friends.GetEnumerator();

            ie.MoveNext();
            Assert.AreEqual("na98me", ie.Current);
            ie.MoveNext();
            Assert.AreEqual(tb2, ie.Current);
            Assert.AreEqual(2, tb2.SomeSet.Count);
            Assert.IsTrue(tb2.SomeSet.Contains("na98me"));
            Assert.IsTrue(tb2.SomeSet.Contains(tb2));
            Assert.AreEqual(4, tb2.SomeMap.Count);
            Assert.AreEqual(tb2, tb2.SomeMap["key1"]);
            Assert.AreEqual("98name", tb2.SomeMap["key2"]);
            TestObject inner1 = (TestObject)tb2.SomeMap["key3"];
            TestObject inner2 = (TestObject)tb2.SomeMap["key4"];

            Assert.AreEqual(0, inner1.Age);
            Assert.AreEqual(null, inner1.Name);
            Assert.AreEqual(98, inner2.Age);
            Assert.AreEqual("namemyvar${", inner2.Name);
        }
        public void SunnyDay()
        {
            StaticApplicationContext ac = new StaticApplicationContext();

            MutablePropertyValues pvs = new MutablePropertyValues();
            pvs.Add("age", "${age}");
            RootObjectDefinition def
                = new RootObjectDefinition("${fqn}", new ConstructorArgumentValues(), pvs);
            ac.RegisterObjectDefinition("tb3", def);

            pvs = new MutablePropertyValues();
            pvs.Add("age", "${age}");
            pvs.Add("name", "name${var}${");
            pvs.Add("spouse", new RuntimeObjectReference("${ref}"));
            ac.RegisterSingleton("tb1", typeof (TestObject), pvs);

            ConstructorArgumentValues cas = new ConstructorArgumentValues();
            cas.AddIndexedArgumentValue(1, "${age}");
            cas.AddGenericArgumentValue("${var}name${age}");

            pvs = new MutablePropertyValues();
            ArrayList friends = new ManagedList();
            friends.Add("na${age}me");
            friends.Add(new RuntimeObjectReference("${ref}"));
            pvs.Add("friends", friends);

            ISet someSet = new ManagedSet();
            someSet.Add("na${age}me");
            someSet.Add(new RuntimeObjectReference("${ref}"));
            pvs.Add("someSet", someSet);

            IDictionary someDictionary = new ManagedDictionary();
            someDictionary["key1"] = new RuntimeObjectReference("${ref}");
            someDictionary["key2"] = "${age}name";
            MutablePropertyValues innerPvs = new MutablePropertyValues();
            someDictionary["key3"] = new RootObjectDefinition(typeof (TestObject), innerPvs);
            someDictionary["key4"] = new ChildObjectDefinition("tb1", innerPvs);
            pvs.Add("someMap", someDictionary);

            RootObjectDefinition definition = new RootObjectDefinition(typeof (TestObject), cas, pvs);
            ac.DefaultListableObjectFactory.RegisterObjectDefinition("tb2", definition);

            pvs = new MutablePropertyValues();
            pvs.Add("Properties", "<spring-config><add key=\"age\" value=\"98\"/><add key=\"var\" value=\"${m}var\"/><add key=\"ref\" value=\"tb2\"/><add key=\"m\" value=\"my\"/><add key=\"fqn\" value=\"Spring.Objects.TestObject, Spring.Core.Tests\"/></spring-config>");
            ac.RegisterSingleton("configurer", typeof (PropertyPlaceholderConfigurer), pvs);
            ac.Refresh();

            TestObject tb1 = (TestObject) ac.GetObject("tb1");
            TestObject tb2 = (TestObject) ac.GetObject("tb2");
            TestObject tb3 = (TestObject) ac.GetObject("tb3");
            Assert.AreEqual(98, tb1.Age);
            Assert.AreEqual(98, tb2.Age);
            Assert.AreEqual(98, tb3.Age);
            Assert.AreEqual("namemyvar${", tb1.Name);
            Assert.AreEqual("myvarname98", tb2.Name);
            Assert.AreEqual(tb2, tb1.Spouse);
            Assert.AreEqual(2, tb2.Friends.Count);
            IEnumerator ie = tb2.Friends.GetEnumerator();
            ie.MoveNext();
            Assert.AreEqual("na98me", ie.Current);
            ie.MoveNext();
            Assert.AreEqual(tb2, ie.Current);
            Assert.AreEqual(2, tb2.SomeSet.Count);
            Assert.IsTrue(tb2.SomeSet.Contains("na98me"));
            Assert.IsTrue(tb2.SomeSet.Contains(tb2));
            Assert.AreEqual(4, tb2.SomeMap.Count);
            Assert.AreEqual(tb2, tb2.SomeMap["key1"]);
            Assert.AreEqual("98name", tb2.SomeMap["key2"]);
            TestObject inner1 = (TestObject) tb2.SomeMap["key3"];
            TestObject inner2 = (TestObject) tb2.SomeMap["key4"];
            Assert.AreEqual(0, inner1.Age);
            Assert.AreEqual(null, inner1.Name);
            Assert.AreEqual(98, inner2.Age);
            Assert.AreEqual("namemyvar${", inner2.Name);
        }
        ///// <summary>
        ///// Given a property value, return a value, resolving any references to other
        ///// objects in the factory if necessary.
        ///// </summary>
        ///// <remarks>
        ///// <p>
        ///// The value could be :
        ///// <list type="bullet">
        ///// <item>
        ///// <p>
        ///// An <see cref="Spring.Objects.Factory.Config.IObjectDefinition"/>,
        ///// which leads to the creation of a corresponding new object instance.
        ///// Singleton flags and names of such "inner objects" are always ignored: inner objects
        ///// are anonymous prototypes.
        ///// </p>
        ///// </item>
        ///// <item>
        ///// <p>
        ///// A <see cref="Spring.Objects.Factory.Config.RuntimeObjectReference"/>, which must
        ///// be resolved.
        ///// </p>
        ///// </item>
        ///// <item>
        ///// <p>
        ///// An <see cref="Spring.Objects.Factory.Support.IManagedCollection"/>. This is a
        ///// special placeholder collection that may contain
        ///// <see cref="Spring.Objects.Factory.Config.RuntimeObjectReference"/>s or
        ///// collections that will need to be resolved.
        ///// </p>
        ///// </item>
        ///// <item>
        ///// <p>
        ///// An ordinary object or <see langword="null"/>, in which case it's left alone.
        ///// </p>
        ///// </item>
        ///// </list>
        ///// </p>
        ///// </remarks>
        ///// <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>
//        protected object ResolveValueIfNecessary(string name, RootObjectDefinition definition, string argumentName, object argumentValue)
//        {
//            object resolvedValue = null;
//
//            AssertUtils.ArgumentNotNull(resolvedValue, "test");
//
//            // 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 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 variables = null;
//
//                if (expHolder.Properties != null)
//                {
//                    PropertyValue contextProperty = expHolder.Properties.GetPropertyValue("Context");
//                    context = contextProperty == null
//                                         ? null
//                                         : ResolveValueIfNecessary2(name, definition, "Context",
//                                                                   contextProperty.Value);
//                    PropertyValue variablesProperty = expHolder.Properties.GetPropertyValue("Variables");
//                    object vars = (variablesProperty == null
//                                                   ? null
//                                                   : ResolveValueIfNecessary2(name, definition, "Variables",
//                                                                             variablesProperty.Value));
//                    if (vars is IDictionary)
//                    {
//                        variables = (IDictionary)vars;
//                    }
//                    else
//                    {
//                        if (vars != null) throw new ArgumentException("'Variables' must resolve to an IDictionary");
//                    }
//                }
//
//                if (variables == null) variables = CollectionsUtil.CreateCaseInsensitiveHashtable();
//                // add 'this' objectfactory reference to variables
//                variables.Add(Expression.ReservedVariableNames.CurrentObjectFactory, this);
//
//                resolvedValue = expHolder.Expression.GetValue(context, variables);
//            }
//            else if (argumentValue is IManagedCollection)
//            {
//                resolvedValue =
//                        ((IManagedCollection)argumentValue).Resolve(name, definition, argumentName,
//                                                                     new ManagedCollectionElementResolver(ResolveValueIfNecessary2));
//            }
//            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;
//        }

        ///// <summary>
        ///// Resolve the target type of the passed <see cref="TypedStringValue"/>.
        ///// </summary>
        ///// <param name="value">The <see cref="TypedStringValue"/> who's target type is to be resolved</param>
        ///// <returns>The resolved target type, if any. <see lang="null" /> otherwise.</returns>
//        protected virtual Type ResolveTargetType(TypedStringValue value)
//        {
//            if (value.HasTargetType)
//            {
//                return value.TargetType;
//            }
//            else
//            {
//                return null;
//            }
//        }

        ///// <summary>
        ///// Resolves an inner object definition.
        ///// </summary>
        ///// <param name="name">
        ///// The name of the object that surrounds this inner object definition.
        ///// </param>
        ///// <param name="innerObjectName">
        ///// The name of the inner object definition... note: this is a synthetic
        ///// name assigned by the factory (since it makes no sense for inner object
        ///// definitions to have names).
        ///// </param>
        ///// <param name="argumentName">
        ///// The name of the property the value of which is being resolved.
        ///// </param>
        ///// <param name="definition">
        ///// The definition of the inner object that is to be resolved.
        ///// </param>
        ///// <param name="singletonOwner">
        ///// <see langword="true"/> if the owner of the property is a singleton.
        ///// </param>
        ///// <returns>
        ///// The resolved object as defined by the inner object definition.
        ///// </returns>
//        protected object ResolveInnerObjectDefinition(string name, string innerObjectName, string argumentName, IObjectDefinition definition,
//                                                      bool singletonOwner)
//        {
//            RootObjectDefinition mod = GetMergedObjectDefinition(innerObjectName, definition);
//            mod.IsSingleton = singletonOwner;
//            object instance;
//            object result;
//            try
//            {
//                instance = InstantiateObject(innerObjectName, mod, ObjectUtils.EmptyObjects, false, false);
//                result = GetObjectForInstance(innerObjectName, instance);
//            }
//            catch (ObjectsException ex)
//            {
//                throw ObjectCreationException.GetObjectCreationException(ex, name, argumentName, definition.ResourceDescription, innerObjectName);
//            }
//            if (singletonOwner && instance is IDisposable)
//            {
//                // keep a reference to the inner object instance, to be able to destroy
//                // it on factory shutdown...
//                DisposableInnerObjects.Add(instance);
//            }
//            return result;
//        }

        /// <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 object ResolveReference(IConfigurableObjectDefinition 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 == 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 ParentObjectFactory.GetObject(reference.ObjectName);
                }
                return GetObject(reference.ObjectName);
            }
            catch (ObjectsException ex)
            {
                throw ObjectCreationException.GetObjectCreationException(ex, name, argumentName, definition.ResourceDescription, reference.ObjectName);
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Determines whether the specified RuntimeObjectReference is equal to the current RuntimeObjectReference.
 /// </summary>
 /// <returns>true if the specified RuntimeObjectReference is equal to the current RuntimeObjectReference; otherwise, false.</returns>
 protected bool Equals(RuntimeObjectReference other)
 {
     return string.Equals(_objectName, other._objectName) && _isToParent.Equals(other._isToParent);
 }
 /// <summary>
 /// Determines whether the specified RuntimeObjectReference is equal to the current RuntimeObjectReference.
 /// </summary>
 /// <returns>true if the specified RuntimeObjectReference is equal to the current RuntimeObjectReference; otherwise, false.</returns>
 protected bool Equals(RuntimeObjectReference other)
 {
     return(string.Equals(_objectName, other._objectName) && _isToParent.Equals(other._isToParent));
 }
        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));
        }