示例#1
0
        private ObjectDefinitionHolder ParseTestObjectDefinition(XmlElement rootElement, ParserContext parserContext)
        {
            MutablePropertyValues properties = new MutablePropertyValues();

            XmlNodeList childNodes = rootElement.ChildNodes;

            //Get all properties (from non whitespace nodes)
            foreach (XmlNode childNode in childNodes)
            {
                if (XmlNodeType.Whitespace != childNode.NodeType)
                {
                    properties.Add(new PropertyValue(childNode.LocalName, childNode.InnerText));
                }
            }
            IConfigurableObjectDefinition od = new RootObjectDefinition(typeof(TestObject), null, properties);

            od.IsSingleton = false;

            //HardCoded for now.
            string id = "testObject";

            //id = ObjectDefinitionReaderUtils.GenerateObjectName(od, reader.ObjectReader.Registry);

            return(new ObjectDefinitionHolder(od, id));
        }
        private void InitFactory(DefaultListableObjectFactory factory)
        {
            Console.WriteLine("init factory");
            RootObjectDefinition tee = new RootObjectDefinition(typeof(Tee), true);
            tee.IsLazyInit = true;
            ConstructorArgumentValues teeValues = new ConstructorArgumentValues();
            teeValues.AddGenericArgumentValue("test");
            tee.ConstructorArgumentValues = teeValues;

            RootObjectDefinition bar = new RootObjectDefinition(typeof(BBar), false);
            ConstructorArgumentValues barValues = new ConstructorArgumentValues();
            barValues.AddGenericArgumentValue(new RuntimeObjectReference("tee"));
            barValues.AddGenericArgumentValue(5);
            bar.ConstructorArgumentValues = barValues;

            RootObjectDefinition foo = new RootObjectDefinition(typeof(FFoo), false);
            MutablePropertyValues fooValues = new MutablePropertyValues();
            fooValues.Add("i", 5);
            fooValues.Add("bar", new RuntimeObjectReference("bar"));
            fooValues.Add("copy", new RuntimeObjectReference("bar"));
            fooValues.Add("s", "test");
            foo.PropertyValues = fooValues;

            factory.RegisterObjectDefinition("foo", foo);
            factory.RegisterObjectDefinition("bar", bar);
            factory.RegisterObjectDefinition("tee", tee);
        }
示例#3
0
        /// <summary>
        /// Creates object definition for the validator reference.
        /// </summary>
        /// <param name="element">The action definition element.</param>
        /// <param name="parserContext">The parser helper.</param>
        /// <returns>Generic validation action definition.</returns>
        private IObjectDefinition ParseValidatorReference(XmlElement element, ParserContext parserContext)
        {
            string typeName = "Spring.Validation.ValidatorReference, Spring.Core";
            string name     = GetAttributeValue(element, ValidatorDefinitionConstants.ReferenceNameAttribute);
            string context  = GetAttributeValue(element, ValidatorDefinitionConstants.ReferenceContextAttribute);
            string when     = GetAttributeValue(element, ValidatorDefinitionConstants.WhenAttribute);

            MutablePropertyValues properties = new MutablePropertyValues();

            properties.Add("Name", name);
            if (StringUtils.HasText(context))
            {
                properties.Add("Context", context);
            }
            if (StringUtils.HasText(when))
            {
                properties.Add("When", when);
            }

            IConfigurableObjectDefinition reference =
                parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(typeName, null, parserContext.ReaderContext.Reader.Domain);

            reference.PropertyValues = properties;
            return(reference);
        }
        protected AbstractObjectDefinition(SerializationInfo info, StreamingContext context)
        {
            constructorArgumentValues = (ConstructorArgumentValues)info.GetValue("constructorArgumentValues", typeof(ConstructorArgumentValues));
            propertyValues            = (MutablePropertyValues)info.GetValue("propertyValues", typeof(MutablePropertyValues));
            eventHandlerValues        = (EventValues)info.GetValue("eventHandlerValues", typeof(EventValues));
            methodOverrides           = (MethodOverrides)info.GetValue("methodOverrides", typeof(MethodOverrides));
            resourceDescription       = info.GetString("resourceDescription");
            isSingleton = info.GetBoolean("isSingleton");
            isPrototype = info.GetBoolean("isPrototype");
            isLazyInit  = info.GetBoolean("isLazyInit");
            isAbstract  = info.GetBoolean("isAbstract");
            scope       = info.GetString("scope");
            role        = (ObjectRole)info.GetValue("role", typeof(ObjectRole));

            var objectTypeName = info.GetString("objectTypeName");

            objectType = objectTypeName != null?Type.GetType(objectTypeName) : null;

            autowireMode      = (AutoWiringMode)info.GetValue("autowireMode", typeof(AutoWiringMode));
            dependencyCheck   = (DependencyCheckingMode)info.GetValue("dependencyCheck", typeof(DependencyCheckingMode));
            dependsOn         = (IList <string>)info.GetValue("dependsOn", typeof(IList <string>));
            autowireCandidate = info.GetBoolean("autowireCandidate");
            primary           = info.GetBoolean("primary");
            qualifiers        = (IDictionary <string, AutowireCandidateQualifier>)info.GetValue("qualifiers", typeof(IDictionary <string, AutowireCandidateQualifier>));
            initMethodName    = info.GetString("initMethodName");
            destroyMethodName = info.GetString("destroyMethodName");
            factoryMethodName = info.GetString("factoryMethodName");
            factoryObjectName = info.GetString("factoryObjectName");
        }
 /// <summary>
 /// Creates a new instance of the
 /// <see cref="Spring.Objects.Factory.Support.RootObjectDefinition"/> class
 /// for a singleton, providing property values and constructor arguments.
 /// </summary>
 /// <param name="typeName">
 /// The assembly qualified <see cref="System.Type.FullName"/> of the object to instantiate.
 /// </param>
 /// <param name="properties">
 /// The <see cref="Spring.Objects.MutablePropertyValues"/> to be applied to
 /// a new instance of the object.
 /// </param>
 /// <param name="arguments">
 /// The <see cref="Spring.Objects.Factory.Config.ConstructorArgumentValues"/>
 /// to be applied to a new instance of the object.
 /// </param>
 /// <remarks>
 /// <p>
 /// Takes an object class name to avoid eager loading of the object class.
 /// </p>
 /// </remarks>
 public RootWebObjectDefinition(
     string typeName,
     ConstructorArgumentValues arguments,
     MutablePropertyValues properties)
     : base(typeName, arguments, properties)
 {
 }
        public void InlcludeAncestors()
        {
            const string          defName     = "foo";
            const string          placeholder = "${name}";
            MutablePropertyValues pvs         = new MutablePropertyValues();


            const string theProperty = "name";

            pvs.Add(theProperty, placeholder);
            RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs);

            IConfigurableListableObjectFactory mock = mocks.StrictMock <IConfigurableListableObjectFactory>();

            Expect.Call(mock.GetObjectDefinitionNames(true)).Return(new string[] { defName });
            Expect.Call(mock.GetObjectDefinition(defName, true)).Return(def);
            mocks.ReplayAll();

            VariablePlaceholderConfigurer vpc = new VariablePlaceholderConfigurer();

            vpc.IgnoreUnresolvablePlaceholders = true;
            vpc.VariableSource   = new DictionaryVariableSource(new string[] { "name", "Erich" });
            vpc.IncludeAncestors = true;

            vpc.PostProcessObjectFactory(mock);

            mocks.VerifyAll();
        }
 /// <summary>
 /// Creates a new instance of the
 /// <see cref="Spring.Objects.Factory.Support.RootWebObjectDefinition"/> class
 /// for an .aspx page, providing property values.
 /// </summary>
 /// <param name="pageName">
 /// Name of the .aspx page to instantiate.
 /// </param>
 /// <param name="properties">
 /// The <see cref="Spring.Objects.MutablePropertyValues"/> to be applied to
 /// a new instance of the object.
 /// </param>
 public RootWebObjectDefinition(
     string pageName,
     MutablePropertyValues properties)
     : base(WebObjectUtils.GetPageType(pageName), null, properties)
 {
     _pageName = WebUtils.CombineVirtualPaths(VirtualEnvironment.CurrentExecutionFilePath, pageName);
 }
示例#8
0
        IObjectDefinition IObjectDefinitionParser.ParseElement(XmlElement element, ParserContext parserContext)
        {
            AssertUtils.ArgumentNotNull(parserContext, "parserContext");

            string id          = element.GetAttribute(ObjectDefinitionConstants.IdAttribute);
            string hostBaseUri = element.GetAttribute(HostBaseUriAttribute);
            string timeout     = element.GetAttribute(TimeOutAttribute);

            if (hostBaseUri.IsNullOrEmpty())
            {
                Console.WriteLine("创建Rest客户端实例异常:没有填写hostBaseUri配置");
                Exception ex = new Exception("创建Rest客户端实例异常:没有填写hostBaseUri配置");
                throw ex;
            }
            ConstructorArgumentValues cav = new ConstructorArgumentValues();

            cav.AddNamedArgumentValue("baseUrl", hostBaseUri);
            MutablePropertyValues mpv = new MutablePropertyValues();

            mpv.Add("TimeOut", timeout);
            RootObjectDefinition rod = new RootObjectDefinition(typeof(RestClient), cav, mpv);

            parserContext.Registry.RegisterObjectDefinition(id, rod);
            return(null);
        }
        private void InitFactory(DefaultListableObjectFactory factory)
        {
            Console.WriteLine("init factory");
            RootObjectDefinition tee = new RootObjectDefinition(typeof(Tee), true);

            tee.IsLazyInit = true;
            ConstructorArgumentValues teeValues = new ConstructorArgumentValues();

            teeValues.AddGenericArgumentValue("test");
            tee.ConstructorArgumentValues = teeValues;

            RootObjectDefinition      bar       = new RootObjectDefinition(typeof(BBar), false);
            ConstructorArgumentValues barValues = new ConstructorArgumentValues();

            barValues.AddGenericArgumentValue(new RuntimeObjectReference("tee"));
            barValues.AddGenericArgumentValue(5);
            bar.ConstructorArgumentValues = barValues;

            RootObjectDefinition  foo       = new RootObjectDefinition(typeof(FFoo), false);
            MutablePropertyValues fooValues = new MutablePropertyValues();

            fooValues.Add("i", 5);
            fooValues.Add("bar", new RuntimeObjectReference("bar"));
            fooValues.Add("copy", new RuntimeObjectReference("bar"));
            fooValues.Add("s", "test");
            foo.PropertyValues = fooValues;

            factory.RegisterObjectDefinition("foo", foo);
            factory.RegisterObjectDefinition("bar", bar);
            factory.RegisterObjectDefinition("tee", tee);
        }
        public void SunnyDay()
        {
            StaticApplicationContext ac = new StaticApplicationContext();

            MutablePropertyValues pvs = new MutablePropertyValues();

            pvs.Add("age", "${maxResults}");
            pvs.Add("name", "${name}");
            ac.RegisterSingleton("tb1", typeof(TestObject), pvs);

            IList variableSources             = new ArrayList();
            CommandLineArgsVariableSource vs1 = new CommandLineArgsVariableSource(
                new string[] { "program.exe", "file.txt", "/name:Aleks Seovic", "/framework:Spring.NET" });

            variableSources.Add(vs1);

            ConfigSectionVariableSource vs2 = new ConfigSectionVariableSource();

            vs2.SectionName = "DaoConfiguration";
            variableSources.Add(vs2);


            pvs = new MutablePropertyValues();
            pvs.Add("VariableSources", variableSources);

            ac.RegisterSingleton("configurer", typeof(VariablePlaceholderConfigurer), pvs);
            ac.Refresh();

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

            Assert.AreEqual(1000, tb1.Age);
            Assert.AreEqual("Aleks Seovic", tb1.Name);
        }
示例#11
0
        public void IncludingAncestors()
        {
            const string          defName     = "foo";
            const string          placeholder = "${name}";
            MutablePropertyValues pvs         = new MutablePropertyValues();


            const string theProperty = "name";

            pvs.Add(theProperty, placeholder);
            RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs);

            IConfigurableListableObjectFactory mock = mocks.StrictMock <IConfigurableListableObjectFactory>();

            Expect.Call(mock.GetObjectDefinitionNames(true)).Return(new string[] { defName });
            Expect.Call(mock.GetObjectDefinition(defName, true)).Return(def);
            Expect.Call(delegate { mock.AddEmbeddedValueResolver(null); }).IgnoreArguments();
            mocks.ReplayAll();

            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();

            cfg.IncludeAncestors = true;

            NameValueCollection defaultProperties = new NameValueCollection();
            const string        expectedName      = "Rick Evans";

            defaultProperties.Add(theProperty, expectedName);
            cfg.Properties = defaultProperties;
            cfg.PostProcessObjectFactory(mock);
            Assert.AreEqual(expectedName, def.PropertyValues.GetPropertyValue(theProperty).Value,
                            "Property placeholder value was not replaced with the resolved value.");

            mocks.VerifyAll();
        }
        public void BailsOnUnresolvableVariable()
        {
            StaticApplicationContext ac = new StaticApplicationContext();

            MutablePropertyValues pvs = new MutablePropertyValues();

            pvs.Add("nickname", "${nickname}");
            ac.RegisterSingleton("tb1", typeof(TestObject), pvs);

            IList variableSources = new ArrayList();

            variableSources.Add(new DictionaryVariableSource(new string[] { }));
            pvs = new MutablePropertyValues();
            pvs.Add("VariableSources", variableSources);
            ac.RegisterSingleton("configurer", typeof(VariablePlaceholderConfigurer), pvs);

            try
            {
                ac.Refresh();
                Assert.Fail("something changed wrt VariablePlaceholder resolution");
            }
            catch (ObjectDefinitionStoreException ex)
            {
                Assert.IsTrue(ex.Message.IndexOf("nickname") > -1);
            }
        }
        public void UsesCustomVariablePrefixSuffix()
        {
            StaticApplicationContext ac = new StaticApplicationContext();

            MutablePropertyValues pvs = new MutablePropertyValues();

            pvs.Add("age", "%[maxResults]%");
            pvs.Add("name", "%[name]%");
            ac.RegisterSingleton("tb1", typeof(TestObject), pvs);

            IList variableSources = new ArrayList();

            variableSources.Add(new DictionaryVariableSource(new string[] { "maxResults", "35", "name", "Erich" }));


            pvs = new MutablePropertyValues();
            pvs.Add("VariableSources", variableSources);
            pvs.Add("PlaceholderPrefix", "%[");
            pvs.Add("PlaceholderSuffix", "]%");

            ac.RegisterSingleton("configurer", typeof(VariablePlaceholderConfigurer), pvs);
            ac.Refresh();

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

            Assert.AreEqual(35, tb1.Age);
            Assert.AreEqual("Erich", tb1.Name);
        }
示例#14
0
        /// <summary>
        /// Create the job instance, populating it with property values taken
        /// from the scheduler context, job data map and trigger data map.
        /// </summary>
        protected override object CreateJobInstance(TriggerFiredBundle bundle)
        {
            ObjectWrapper ow = new ObjectWrapper(bundle.JobDetail.JobType);

            if (IsEligibleForPropertyPopulation(ow.WrappedInstance))
            {
                MutablePropertyValues pvs = new MutablePropertyValues();
                if (schedulerContext != null)
                {
                    pvs.AddAll(schedulerContext);
                }
                pvs.AddAll(bundle.JobDetail.JobDataMap);
                pvs.AddAll(bundle.Trigger.JobDataMap);
                if (ignoredUnknownProperties != null)
                {
                    for (int i = 0; i < ignoredUnknownProperties.Length; i++)
                    {
                        string propName = ignoredUnknownProperties[i];
                        if (pvs.Contains(propName))
                        {
                            pvs.Remove(propName);
                        }
                    }
                    ow.SetPropertyValues(pvs);
                }
                else
                {
                    ow.SetPropertyValues(pvs, true);
                }
            }
            return(ow.WrappedInstance);
        }
示例#15
0
        public void WithDefaultProperties()
        {
            const string          defName     = "foo";
            const string          placeholder = "${name}";
            MutablePropertyValues pvs         = new MutablePropertyValues();

            const string theProperty = "name";

            pvs.Add(theProperty, placeholder);
            RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs);

            IConfigurableListableObjectFactory mock = (IConfigurableListableObjectFactory)mocks.CreateMock(typeof(IConfigurableListableObjectFactory));

            Expect.Call(mock.GetObjectDefinitionNames()).Return(new string [] { defName });
            Expect.Call(mock.GetObjectDefinition(defName)).Return(def);
            mocks.ReplayAll();

            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
            NameValueCollection           defaultProperties = new NameValueCollection();
            const string expectedName = "Rick Evans";

            defaultProperties.Add(theProperty, expectedName);
            cfg.Properties = defaultProperties;
            cfg.PostProcessObjectFactory(mock);
            Assert.AreEqual(expectedName, def.PropertyValues.GetPropertyValue(theProperty).Value,
                            "Property placeholder value was not replaced with the resolved value.");

            mocks.VerifyAll();
        }
        public void WithIgnoreUnresolvablePlaceholder()
        {
            const string          defName     = "foo";
            const string          placeholder = "${name}";
            TestObject            foo         = new TestObject(placeholder, 30);
            MutablePropertyValues pvs         = new MutablePropertyValues();

            pvs.Add("name", placeholder);
            RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs);

            IConfigurableListableObjectFactory mock = mocks.StrictMock <IConfigurableListableObjectFactory>();

            Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string [] { defName });
            Expect.Call(mock.GetObjectDefinition(defName, false)).Return(def);
            Expect.Call(() => mock.AddEmbeddedValueResolver(null)).IgnoreArguments();
            mocks.ReplayAll();

            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();

            cfg.IgnoreUnresolvablePlaceholders = true;
            cfg.PostProcessObjectFactory(mock);
            Assert.AreEqual(placeholder, foo.Name);

            mocks.VerifyAll();
        }
示例#17
0
        /// <summary>
        /// Parses the RemotingConfigurer definition.
        /// </summary>
        /// <param name="element">The element to parse.</param>
        /// <param name="name">The name of the object definition.</param>
        /// <param name="parserContext">The parser context.</param>
        /// <returns>RemotingConfigurer object definition.</returns>
        private IConfigurableObjectDefinition ParseRemotingConfigurer(
            XmlElement element, string name, ParserContext parserContext)
        {
            string typeName       = GetTypeName(element);
            string filename       = element.GetAttribute(RemotingConfigurerConstants.FilenameAttribute);
            string useConfigFile  = element.GetAttribute(RemotingConfigurerConstants.UseConfigFileAttribute);
            string ensureSecurity = element.GetAttribute(RemotingConfigurerConstants.EnsureSecurityAttribute);

            MutablePropertyValues properties = new MutablePropertyValues();

            if (StringUtils.HasText(filename))
            {
                properties.Add("Filename", filename);
            }
            if (StringUtils.HasText(useConfigFile))
            {
                properties.Add("UseConfigFile", useConfigFile);
            }
            if (StringUtils.HasText(ensureSecurity))
            {
                properties.Add("EnsureSecurity", ensureSecurity);
            }

            IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
                typeName, null, parserContext.ReaderContext.Reader.Domain);

            cod.PropertyValues = properties;
            return(cod);
        }
示例#18
0
        /// <summary>
        /// Parses the CaoFactoryObject definition.
        /// </summary>
        /// <param name="element">The element to parse.</param>
        /// <param name="name">The name of the object definition.</param>
        /// <param name="parserContext">The parser context.</param>
        /// <returns>CaoFactoryObject object definition.</returns>
        private IConfigurableObjectDefinition ParseCaoFactoryObject(
            XmlElement element, string name, ParserContext parserContext)
        {
            string typeName         = GetTypeName(element);
            string remoteTargetName = element.GetAttribute(CaoFactoryObjectConstants.RemoteTargetNameAttribute);
            string serviceUrl       = element.GetAttribute(CaoFactoryObjectConstants.ServiceUrlAttribute);

            MutablePropertyValues properties = new MutablePropertyValues();

            if (StringUtils.HasText(remoteTargetName))
            {
                properties.Add("RemoteTargetName", remoteTargetName);
            }
            if (StringUtils.HasText(serviceUrl))
            {
                properties.Add("ServiceUrl", serviceUrl);
            }

            foreach (XmlElement child in element.ChildNodes)
            {
                switch (child.LocalName)
                {
                case CaoFactoryObjectConstants.ConstructorArgumentsElement:
                    properties.Add("ConstructorArguments", base.ParseListElement(child, name, parserContext));
                    break;
                }
            }

            IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
                typeName, null, parserContext.ReaderContext.Reader.Domain);

            cod.PropertyValues = properties;

            return(cod);
        }
示例#19
0
 /// <summary>
 /// Creates a new instance of the
 /// <see cref="Oragon.Spring.Objects.Factory.Support.ChildObjectDefinition"/>
 /// class.
 /// </summary>
 /// <param name="parentName">
 /// The name of the parent object.
 /// </param>
 /// <param name="typeName">
 /// The <see cref="System.Type.AssemblyQualifiedName"/> of the object to
 /// instantiate.
 /// </param>
 /// <param name="arguments">
 /// The <see cref="Oragon.Spring.Objects.Factory.Config.ConstructorArgumentValues"/>
 /// to be applied to a new instance of the object.
 /// </param>
 /// <param name="properties">
 /// The additional property values (if any) of the child.
 /// </param>
 public ChildObjectDefinition(
     string parentName, string typeName, ConstructorArgumentValues arguments, MutablePropertyValues properties)
     : base(arguments, properties)
 {
     this.parentName = parentName;
     ObjectTypeName  = typeName;
 }
        public void IncludingAncestors()
        {
            const string          defName     = "foo";
            const string          placeholder = "${name}";
            MutablePropertyValues pvs         = new MutablePropertyValues();


            const string theProperty = "name";

            pvs.Add(theProperty, placeholder);
            RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs);

            IConfigurableListableObjectFactory mock = A.Fake <IConfigurableListableObjectFactory>();

            A.CallTo(() => mock.GetObjectDefinitionNames(true)).Returns(new string[] { defName });
            A.CallTo(() => mock.GetObjectDefinition(defName, true)).Returns(def);

            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();

            cfg.IncludeAncestors = true;

            NameValueCollection defaultProperties = new NameValueCollection();
            const string        expectedName      = "Rick Evans";

            defaultProperties.Add(theProperty, expectedName);
            cfg.Properties = defaultProperties;
            cfg.PostProcessObjectFactory(mock);
            Assert.AreEqual(expectedName, def.PropertyValues.GetPropertyValue(theProperty).Value,
                            "Property placeholder value was not replaced with the resolved value.");

            A.CallTo(() => mock.AddEmbeddedValueResolver(A <IStringValueResolver> ._)).MustHaveHappened();
        }
示例#21
0
        private IObjectDefinition ParseExceptionAction(XmlElement element, ParserContext parserContext)
        {
            string typeName        = "Spring.Validation.Actions.ExceptionAction, Spring.Core";
            string throwExpression = GetAttributeValue(element, ValidatorDefinitionConstants.ThrowAttribute);


            ConstructorArgumentValues ctorArgs = new ConstructorArgumentValues();

            ctorArgs.AddGenericArgumentValue(throwExpression);

            string when = GetAttributeValue(element, ValidatorDefinitionConstants.WhenAttribute);
            MutablePropertyValues properties = new MutablePropertyValues();

            if (StringUtils.HasText(when))
            {
                properties.Add("When", when);
            }

            IConfigurableObjectDefinition action =
                parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(typeName, null, parserContext.ReaderContext.Reader.Domain);

            action.ConstructorArgumentValues = ctorArgs;
            action.PropertyValues            = properties;

            return(action);
        }
        /// <summary>
        /// Creates an error message action based on the specified message element.
        /// </summary>
        /// <param name="message">The message element.</param>
        /// <param name="parserContext">The parser helper.</param>
        /// <returns>The error message action definition.</returns>
        private static IObjectDefinition ParseErrorMessageAction(XmlElement message, ParserContext parserContext)
        {
            string messageId = GetAttributeValue(message, MessageConstants.IdAttribute);
            string[] providers = GetAttributeValue(message, MessageConstants.ProvidersAttribute).Split(',');
            ArrayList parameters = new ArrayList();

            foreach (XmlElement param in message.ChildNodes)
            {
                IExpression paramExpression = Expression.Parse(GetAttributeValue(param, MessageConstants.ParameterValueAttribute));
                parameters.Add(paramExpression);
            }

            string typeName = "Spring.Validation.Actions.ErrorMessageAction, Spring.Core";
            ConstructorArgumentValues ctorArgs = new ConstructorArgumentValues();
            ctorArgs.AddGenericArgumentValue(messageId);
            ctorArgs.AddGenericArgumentValue(providers);

            string when = GetAttributeValue(message, ValidatorDefinitionConstants.WhenAttribute);
            MutablePropertyValues properties = new MutablePropertyValues();
            if (StringUtils.HasText(when))
            {
                properties.Add("When", when);
            }
            if (parameters.Count > 0)
            {
                properties.Add("Parameters", parameters.ToArray(typeof(IExpression)));
            }

            IConfigurableObjectDefinition action =
                parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(typeName, null, parserContext.ReaderContext.Reader.Domain);
            action.ConstructorArgumentValues = ctorArgs;
            action.PropertyValues = properties;

            return action;
        }
 /// <summary>
 /// Parses the attribute of the given <paramref name="attName"/> from the XmlElement and, if available, adds a property of the given <paramref name="propName"/> with
 /// the parsed value.
 /// </summary>
 private void ParseAttributeIntoProperty(XmlElement element, string attName, MutablePropertyValues properties, string propName)
 {
     string test = GetAttributeValue(element, attName);
     if (StringUtils.HasText(test))
     {
         properties.Add(propName, test);
     }
 }
 /// <summary>
 /// Creates a new instance of the
 /// <see cref="Spring.Objects.Factory.Support.AbstractObjectDefinition"/>
 /// class.
 /// </summary>
 /// <remarks>
 /// <p>
 /// This is an <see langword="abstract"/> class, and as such exposes no
 /// public constructors.
 /// </p>
 /// </remarks>
 protected AbstractObjectDefinition(ConstructorArgumentValues arguments, MutablePropertyValues properties)
 {
     constructorArgumentValues =
         (arguments != null) ? arguments : new ConstructorArgumentValues();
     propertyValues =
         (properties != null) ? properties : new MutablePropertyValues();
     eventHandlerValues = new EventValues();
     DependsOn = StringUtils.EmptyStrings;
 }
 /// <summary>
 /// Creates a new instance of the
 /// <see cref="Spring.Objects.Factory.Support.AbstractObjectDefinition"/>
 /// class.
 /// </summary>
 /// <remarks>
 /// <p>
 /// This is an <see langword="abstract"/> class, and as such exposes no
 /// public constructors.
 /// </p>
 /// </remarks>
 protected AbstractObjectDefinition(ConstructorArgumentValues arguments, MutablePropertyValues properties)
 {
     constructorArgumentValues =
         (arguments != null) ? arguments : new ConstructorArgumentValues();
     propertyValues =
         (properties != null) ? properties : new MutablePropertyValues();
     eventHandlerValues = new EventValues();
     DependsOn          = StringUtils.EmptyStrings;
 }
示例#26
0
        /// <summary>
        /// Creates a spring resource loader by setting the ResourceLoaderPaths of the
        /// engine factory (the resource loader itself will be created internally either as
        /// spring or as file resource loader based on the value of prefer-file-system-access
        /// attribute).
        /// </summary>
        /// <param name="elements">list of resource loader path elements</param>
        /// <param name="objectDefinitionProperties">the MutablePropertyValues to set the property for the engine factory</param>
        private void AppendResourceLoaderPaths(XmlNodeList elements, MutablePropertyValues objectDefinitionProperties)
        {
            IList <string> paths = new List <string>();

            foreach (XmlElement element in elements)
            {
                string path = GetAttributeValue(element, TemplateDefinitionConstants.AttributeUri);
                paths.Add(path);
            }
            objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyResourceLoaderPaths, paths);
        }
示例#27
0
        public void WithUnresolvableEnvironmentProperty()
        {
            StaticApplicationContext ac  = new StaticApplicationContext();
            MutablePropertyValues    pvs = new MutablePropertyValues();

            pvs.Add("touchy", "${PROCESSOR_ARCHITECTURE}");
            ac.RegisterSingleton("to", typeof(TestObject), pvs);

            pvs = new MutablePropertyValues();
            pvs.Add("environmentVariableMode", EnvironmentVariableMode.Never);
            ac.RegisterSingleton("configurer", typeof(PropertyPlaceholderConfigurer), pvs);
            ac.Refresh();
        }
        public void WithUnresolvableEnvironmentProperty()
        {
            StaticApplicationContext ac  = new StaticApplicationContext();
            MutablePropertyValues    pvs = new MutablePropertyValues();

            pvs.Add("touchy", "${PROCESSOR_ARCHITECTURE}");
            ac.RegisterSingleton("to", typeof(TestObject), pvs);

            pvs = new MutablePropertyValues();
            pvs.Add("environmentVariableMode", EnvironmentVariableMode.Never);
            ac.RegisterSingleton("configurer", typeof(PropertyPlaceholderConfigurer), pvs);
            Assert.Throws <ObjectDefinitionStoreException>(() => ac.Refresh(), "Error registering object with name 'to' defined in '' : Could not resolve placeholder 'PROCESSOR_ARCHITECTURE'.");
        }
示例#29
0
        /// <summary>
        /// Parses the SaoExporter definition.
        /// </summary>
        /// <param name="element">The element to parse.</param>
        /// <param name="name">The name of the object definition.</param>
        /// <param name="parserContext">The parser context.</param>
        /// <returns>SaoExporter object definition.</returns>
        private IConfigurableObjectDefinition ParseSaoExporter(
            XmlElement element, string name, ParserContext parserContext)
        {
            string typeName        = GetTypeName(element);
            string targetName      = element.GetAttribute(SaoExporterConstants.TargetNameAttribute);
            string applicationName = element.GetAttribute(SaoExporterConstants.ApplicationNameAttribute);
            string serviceName     = element.GetAttribute(SaoExporterConstants.ServiceNameAttribute);
            string infinite        = element.GetAttribute(SaoExporterConstants.InfiniteAttribute);

            MutablePropertyValues properties = new MutablePropertyValues();

            if (StringUtils.HasText(targetName))
            {
                properties.Add("TargetName", targetName);
            }
            if (StringUtils.HasText(applicationName))
            {
                properties.Add("ApplicationName", applicationName);
            }
            if (StringUtils.HasText(serviceName))
            {
                properties.Add("ServiceName", serviceName);
            }
            if (StringUtils.HasText(infinite))
            {
                properties.Add("Infinite", infinite);
            }

            foreach (XmlElement child in element.ChildNodes)
            {
                switch (child.LocalName)
                {
                case LifeTimeConstants.LifeTimeElement:
                    ParseLifeTime(properties, child, parserContext);
                    break;

                case InterfacesConstants.InterfacesElement:
                    properties.Add("Interfaces", base.ParseListElement(child, name, parserContext));
                    break;
                }
            }

            IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
                typeName, null, parserContext.ReaderContext.Reader.Domain);

            cod.PropertyValues = properties;
            return(cod);
        }
示例#30
0
 /// <summary>
 /// This implementation applies the passed-in job data map as object property
 /// values, and delegates to <code>ExecuteInternal</code> afterwards.
 /// </summary>
 /// <seealso cref="ExecuteInternal" />
 public void Execute(IJobExecutionContext context)
 {
     try
     {
         ObjectWrapper         bw  = new ObjectWrapper(this);
         MutablePropertyValues pvs = new MutablePropertyValues();
         pvs.AddAll(context.Scheduler.Context);
         pvs.AddAll(context.MergedJobDataMap);
         bw.SetPropertyValues(pvs, true);
     }
     catch (SchedulerException ex)
     {
         throw new JobExecutionException(ex);
     }
     ExecuteInternal(context);
 }
        /// <summary>
        /// Creates a generic action based on the specified element.
        /// </summary>
        /// <param name="element">The action definition element.</param>
        /// <param name="parserContext">The parser helper.</param>
        /// <returns>Generic validation action definition.</returns>
        private IObjectDefinition ParseGenericAction(XmlElement element, ParserContext parserContext)
        {
            string typeName = GetAttributeValue(element, ObjectDefinitionConstants.TypeAttribute);
            string when = GetAttributeValue(element, ValidatorDefinitionConstants.WhenAttribute);
            MutablePropertyValues properties = base.ParsePropertyElements("validator:action", element, parserContext);
            if (StringUtils.HasText(when))
            {
                properties.Add("When", when);
            }

            IConfigurableObjectDefinition action =
                parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(typeName, null, parserContext.ReaderContext.Reader.Domain);
            action.PropertyValues = properties;

            return action;
        }
        public void WithEnvironmentVariableFallback()
        {
            StaticApplicationContext ac  = new StaticApplicationContext();
            MutablePropertyValues    pvs = new MutablePropertyValues();

            pvs.Add("touchy", "${PROCESSOR_ARCHITECTURE}");
            ac.RegisterSingleton("to", typeof(TestObject), pvs);

            pvs = new MutablePropertyValues();
            ac.RegisterSingleton("configurer", typeof(PropertyPlaceholderConfigurer), pvs);
            ac.Refresh();

            TestObject to = (TestObject)ac["to"];

            Assert.AreEqual(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"),
                            to.Touchy);
        }
        public void ChainedResolution()
        {
            StaticApplicationContext ac = new StaticApplicationContext();

            MutablePropertyValues pvs = new MutablePropertyValues();
            pvs.Add("name", "${name}");
            pvs.Add("nickname", "${nickname}");
            ac.RegisterSingleton("tb1", typeof(TestObject), pvs);

            IList variableSources = new ArrayList();
            variableSources.Add(new DictionaryVariableSource(new string[] { "name", "name-value" }));
            variableSources.Add(new DictionaryVariableSource(new string[] { "nickname", "nickname-value" }));
            VariablePlaceholderConfigurer vphc = new VariablePlaceholderConfigurer(variableSources);
            ac.AddObjectFactoryPostProcessor(vphc);
            ac.Refresh();

            TestObject tb1 = (TestObject)ac.GetObject("tb1");
            Assert.AreEqual("name-value", tb1.Name);
            Assert.AreEqual("nickname-value", tb1.Nickname);
        }
 public void AddPropertyValue()
 {
     StaticApplicationContext ac = new StaticApplicationContext();
     ac.RegisterSingleton("tb1", typeof(TestObject), new MutablePropertyValues());
     ac.RegisterSingleton("tb2", typeof(TestObject), new MutablePropertyValues());
     MutablePropertyValues pvs = new MutablePropertyValues();
     pvs.Add("Properties", "<spring-config><add key=\"tb1.Age\" value=\"99\"/><add key=\"tb2.Name\" value=\"test\"/></spring-config>");
     ac.RegisterSingleton("configurer1", typeof(PropertyOverrideConfigurer), pvs);
     pvs = new MutablePropertyValues();
     pvs.Add("Properties", "<spring-config><add key=\"tb2.Age\" value=\"99\"/><add key=\"tb2.Name\" value=\"test\"/></spring-config>");
     pvs.Add("order", "0");
     ac.RegisterSingleton("configurer2", typeof(PropertyOverrideConfigurer), pvs);
     ac.Refresh();
     TestObject tb1 = (TestObject)ac.GetObject("tb1");
     TestObject tb2 = (TestObject)ac.GetObject("tb2");
     Assert.AreEqual(99, tb1.Age);
     Assert.AreEqual(99, tb2.Age);
     Assert.AreEqual(null, tb1.Name);
     Assert.AreEqual("test", tb2.Name);
 }
        public void BailsOnUnresolvableVariable()
        {
            StaticApplicationContext ac = new StaticApplicationContext();

            MutablePropertyValues pvs = new MutablePropertyValues();
            pvs.Add("nickname", "${nickname}");
            ac.RegisterSingleton("tb1", typeof(TestObject), pvs);

            IList variableSources = new ArrayList();
            variableSources.Add(new DictionaryVariableSource(new string[] { }));
            pvs = new MutablePropertyValues();
            pvs.Add("VariableSources", variableSources);
            ac.RegisterSingleton("configurer", typeof(VariablePlaceholderConfigurer), pvs);

            try
            {
                ac.Refresh();
                Assert.Fail("something changed wrt VariablePlaceholder resolution");
            }
            catch (ObjectDefinitionStoreException ex)
            {
                Assert.IsTrue(ex.Message.IndexOf("nickname") > -1);
            }
        }
 public void CustomEditor()
 {
     DefaultListableObjectFactory lof = new DefaultListableObjectFactory();
     NumberFormatInfo nfi = new CultureInfo("en-GB", false).NumberFormat;
     lof.RegisterCustomConverter(typeof(Single), new CustomNumberConverter(typeof(Single), nfi, true));
     MutablePropertyValues pvs = new MutablePropertyValues();
     pvs.Add("myFloat", "1.1");
     lof.RegisterObjectDefinition("testObject", new RootObjectDefinition(typeof(TestObject), pvs));
     TestObject testObject = (TestObject)lof.GetObject("testObject");
     Assert.IsTrue(testObject.MyFloat == 1.1f);
 }
        /// <summary>
        /// Creates a new instance of the
        /// <see cref="Spring.Objects.Factory.Support.AbstractObjectDefinition"/>
        /// class.
        /// </summary>
        /// <param name="other">
        /// The object definition used to initialise the member fields of this
        /// instance.
        /// </param>
        /// <remarks>
        /// <p>
        /// This is an <see langword="abstract"/> class, and as such exposes no
        /// public constructors.
        /// </p>
        /// </remarks>
        protected AbstractObjectDefinition(IObjectDefinition other)
        {
            AssertUtils.ArgumentNotNull(other, "other");
            this.OverrideFrom(other);

            AbstractObjectDefinition aod = other as AbstractObjectDefinition;
            if (aod != null)
            {
                if (aod.HasObjectType)
                {
                    ObjectType = other.ObjectType;
                }
                else
                {
                    ObjectTypeName = other.ObjectTypeName;
                }
                MethodOverrides = new MethodOverrides(aod.MethodOverrides);
                DependencyCheck = aod.DependencyCheck;
            }
            ParentName = other.ParentName;
            IsAbstract = other.IsAbstract;
//            IsSingleton = other.IsSingleton;
            Scope = other.Scope;
            Role = other.Role;
            IsLazyInit = other.IsLazyInit;
            ConstructorArgumentValues
                = new ConstructorArgumentValues(other.ConstructorArgumentValues);
            PropertyValues = new MutablePropertyValues(other.PropertyValues);
            EventHandlerValues = new EventValues(other.EventHandlerValues);

            InitMethodName = other.InitMethodName;
            DestroyMethodName = other.DestroyMethodName;
            DependsOn = new string[other.DependsOn.Length];
            IsAutowireCandidate = other.IsAutowireCandidate;
            Array.Copy(other.DependsOn, DependsOn, other.DependsOn.Length);
            FactoryMethodName = other.FactoryMethodName;
            FactoryObjectName = other.FactoryObjectName;
            AutowireMode = other.AutowireMode;
            ResourceDescription = other.ResourceDescription;
        }
 /// <summary>
 /// Creates a new instance of the
 /// <see cref="Spring.Objects.Factory.Support.RootObjectDefinition"/> class
 /// for a singleton, providing property values and constructor arguments.
 /// </summary>
 /// <param name="typeName">
 /// The assembly qualified <see cref="System.Type.FullName"/> of the object to instantiate.
 /// </param>
 /// <param name="properties">
 /// The <see cref="Spring.Objects.MutablePropertyValues"/> to be applied to
 /// a new instance of the object.
 /// </param>
 /// <param name="arguments">
 /// The <see cref="Spring.Objects.Factory.Config.ConstructorArgumentValues"/>
 /// to be applied to a new instance of the object.
 /// </param>
 /// <remarks>
 /// <p>
 /// Takes an object class name to avoid eager loading of the object class.
 /// </p>
 /// </remarks>
 public RootWebObjectDefinition(
     string typeName,
     ConstructorArgumentValues arguments,
     MutablePropertyValues properties)
     : base(typeName, arguments, properties)
 {}
 /// <summary>
 /// Parse property value subelements of the given object element.
 /// </summary>
 /// <param name="name">
 /// The name of the object (definition) associated with the property element (s)
 /// </param>
 /// <param name="element">
 /// The element containing the top level object definition.
 /// </param>
 /// <param name="parserContext">
 /// The namespace-aware parser.
 /// </param>
 /// <returns>
 /// The property (s) associated with the object (definition).
 /// </returns>
 protected virtual MutablePropertyValues ParsePropertyElements(
     string name, XmlElement element, ParserContext parserContext)
 {
     MutablePropertyValues properties = new MutablePropertyValues();
     foreach (XmlNode node in this.SelectNodes(element, ObjectDefinitionConstants.PropertyElement))
     {
         ParsePropertyElement(name, properties, (XmlElement)node, parserContext);
     }
     return properties;
 }
 public void AutowireWithParent()
 {
     XmlObjectFactory xof = new XmlObjectFactory(new ReadOnlyXmlTestResource("autowire.xml", GetType()));
     DefaultListableObjectFactory lbf = new DefaultListableObjectFactory();
     MutablePropertyValues pvs = new MutablePropertyValues();
     pvs.Add("Name", "kerry");
     lbf.RegisterObjectDefinition("Spouse", new RootObjectDefinition(typeof(TestObject), pvs));
     xof.ParentObjectFactory = lbf;
     DoTestAutowire(xof);
 }
 public void ExtensiveCircularReference()
 {
     DefaultListableObjectFactory lof = new DefaultListableObjectFactory();
     for (int i = 0; i < 1000; i++)
     {
         MutablePropertyValues pvs = new MutablePropertyValues();
         pvs.Add(new PropertyValue("Spouse", new RuntimeObjectReference("object" + (i < 99 ? i + 1 : 0))));
         RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject), pvs);
         lof.RegisterObjectDefinition("object" + i, rod);
     }
     lof.PreInstantiateSingletons();
     for (int i = 0; i < 1000; i++)
     {
         TestObject obj = (TestObject)lof.GetObject("object" + i);
         TestObject otherObj = (TestObject)lof.GetObject("object" + (i < 99 ? i + 1 : 0));
         Assert.IsTrue(obj.Spouse == otherObj);
     }
 }
 public void AutowireWithSatisfiedConstructorDependency()
 {
     DefaultListableObjectFactory lof = new DefaultListableObjectFactory();
     MutablePropertyValues pvs = new MutablePropertyValues();
     pvs.Add(new PropertyValue("name", "Rod"));
     RootObjectDefinition rood = new RootObjectDefinition(typeof(TestObject), pvs);
     lof.RegisterObjectDefinition("rod", rood);
     Assert.AreEqual(1, lof.ObjectDefinitionCount);
     object registered = lof.Autowire(typeof(ConstructorDependency), AutoWiringMode.AutoDetect, false);
     Assert.AreEqual(1, lof.ObjectDefinitionCount);
     ConstructorDependency kerry = (ConstructorDependency)registered;
     TestObject rod = (TestObject)lof.GetObject("rod");
     Assert.AreSame(rod, kerry._spouse);
 }
 public void ApplyPropertyValuesWithIncompleteDefinition()
 {
     DefaultListableObjectFactory factory = new DefaultListableObjectFactory();
     MutablePropertyValues properties = new MutablePropertyValues();
     properties.Add("age", "99");
     factory.RegisterObjectDefinition("test", new RootObjectDefinition(null, properties));
     TestObject obj = new TestObject();
     Assert.AreEqual(0, obj.Age);
     factory.ApplyObjectPropertyValues(obj, "test");
     Assert.AreEqual(99, obj.Age, "Property values were not applied to the existing instance.");
 }
        public void OverridePropertyReference()
        {
            StaticApplicationContext ac = new StaticApplicationContext();

            MutablePropertyValues pvs = new MutablePropertyValues();
            pvs.Add("Spouse", new RuntimeObjectReference("spouse1"));
            ac.RegisterSingleton("tb1", typeof(TestObject), pvs);

            ac.RegisterSingleton("spouse1", typeof(TestObject), new MutablePropertyValues());
            ac.RegisterSingleton("spouse2", typeof(TestObject), new MutablePropertyValues());

            pvs = new MutablePropertyValues();
            pvs.Add("Properties", "<spring-config><add key=\"tb1.Spouse\" value=\"spouse2\"/></spring-config>");
            ac.RegisterSingleton("configurer", typeof(PropertyOverrideConfigurer), pvs);

            ac.Refresh();
            TestObject tb1 = (TestObject)ac.GetObject("tb1");
            TestObject spouse2 = (TestObject)ac.GetObject("spouse2");
            Assert.AreEqual(spouse2, tb1.Spouse);
        }
 public void RegisterExistingSingletonWithAutowire()
 {
     DefaultListableObjectFactory lof = new DefaultListableObjectFactory();
     MutablePropertyValues pvs = new MutablePropertyValues();
     pvs.Add("name", "Tony");
     pvs.Add("age", "48");
     RootObjectDefinition rod = new RootObjectDefinition(typeof(DependenciesObject), pvs, true);
     rod.DependencyCheck = DependencyCheckingMode.Objects;
     rod.AutowireMode = AutoWiringMode.ByType;
     lof.RegisterObjectDefinition("test", rod);
     object singletonObject = new TestObject();
     lof.RegisterSingleton("singletonObject", singletonObject);
     Assert.IsTrue(lof.ContainsObject("singletonObject"));
     Assert.IsTrue(lof.IsSingleton("singletonObject"));
     Assert.AreEqual(0, lof.GetAliases("singletonObject").Count);
     DependenciesObject test = (DependenciesObject)lof.GetObject("test");
     Assert.AreEqual(singletonObject, lof.GetObject("singletonObject"));
     Assert.AreEqual(singletonObject, test.Spouse);
 }
 /// <summary>
 /// Creates a new instance of the
 /// <see cref="Spring.Objects.Factory.Support.ChildWebObjectDefinition"/> class
 /// for a singleton, providing property values and constructor arguments.
 /// </summary>
 /// <param name="parentName">Name of the parent object definition.</param>
 /// <param name="typeName">The class name of the object to instantiate.</param>
 /// <param name="arguments">
 /// The <see cref="Spring.Objects.Factory.Config.ConstructorArgumentValues"/>
 /// to be applied to a new instance of the object.
 /// </param>
 /// <param name="properties">
 /// The <see cref="Spring.Objects.MutablePropertyValues"/> to be applied to
 /// a new instance of the object.
 /// </param>
 public ChildWebObjectDefinition(string parentName, string typeName, ConstructorArgumentValues arguments, MutablePropertyValues properties) 
     : base(parentName, typeName, arguments, properties)
 {}
 public void AutowireWithUnsatisfiedConstructorDependency()
 {
     DefaultListableObjectFactory lof = new DefaultListableObjectFactory();
     MutablePropertyValues pvs = new MutablePropertyValues();
     pvs.Add(new PropertyValue("name", "Rod"));
     RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject), pvs);
     lof.RegisterObjectDefinition("rod", rod);
     Assert.AreEqual(1, lof.ObjectDefinitionCount);
     lof.Autowire(typeof(UnsatisfiedConstructorDependency), AutoWiringMode.AutoDetect, true);
     Assert.Fail("Should have unsatisfied constructor dependency on SideEffectObject");
 }
        public void CreateObjectDoesNotConfigure()
        {
            using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory())
            {
                MutablePropertyValues properties = new MutablePropertyValues();
                properties.Add(new PropertyValue("Age", 27));
                properties.Add(new PropertyValue("Name", "Bruno"));
                RootObjectDefinition singleton = new RootObjectDefinition(typeof(TestObject), null, properties);
                singleton.IsSingleton = true;
                lof.RegisterObjectDefinition("singleton", singleton);

                TestObject to2 = lof.CreateObject("singleton", typeof(TestObject), null) as TestObject;
                Assert.IsNotNull(to2);
                // no props set
                Assert.AreEqual(0, to2.Age);
                Assert.AreEqual(null, to2.Name);
                // no object postprocessors executed!
                Assert.AreEqual(null, to2.ObjectName);
                Assert.AreEqual(null, to2.ObjectFactory);
                Assert.AreEqual(null, to2.SharedState);
            }
        }
        public void PullingObjectWithFactoryMethodAlsoInjectsDependencies()
        {
            string expectedName = "Terese Raquin";
            MutablePropertyValues props = new MutablePropertyValues();
            props.Add(new PropertyValue("Name", expectedName));

            RootObjectDefinition def = new RootObjectDefinition(typeof(MySingleton), props);
            def.FactoryMethodName = "GetInstance";

            DefaultListableObjectFactory fac = new DefaultListableObjectFactory();
            fac.RegisterObjectDefinition("foo", def);

            object foo = fac["foo"];
            Assert.IsNotNull(foo, "Couldn't pull manually registered instance out of the factory using factory method instantiation.");
            MySingleton sing = (MySingleton)foo;
            Assert.AreEqual(expectedName, sing.Name, "Dependency was not resolved pulling manually registered instance out of the factory using factory method instantiation.");
        }
        public void CreateObjectDoesAffectContainerManagedSingletons()
        {
            using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory())
            {
                lof.AddObjectPostProcessor(new SharedStateAwareProcessor(new ISharedStateFactory[] { new ByTypeSharedStateFactory() }, Int32.MaxValue ));

                MutablePropertyValues properties = new MutablePropertyValues();
                properties.Add(new PropertyValue("Age", 27));
                properties.Add(new PropertyValue("Name", "Bruno"));
                RootObjectDefinition singleton = new RootObjectDefinition(typeof(TestObject), null, properties);
                singleton.IsSingleton = true;
                lof.RegisterObjectDefinition("singleton", singleton);

                // a call to GetObject() results in a normally configured instance
                TestObject to = lof.GetObject("singleton") as TestObject;
                Assert.IsNotNull(to);
                // props set
                Assert.AreEqual(27, to.Age);
                Assert.AreEqual("Bruno", to.Name);
                // object postprocessors executed!
                Assert.AreEqual("singleton", to.ObjectName);
                Assert.AreEqual(lof, to.ObjectFactory);
                Assert.IsNotNull(to.SharedState);

                // altough configured as singleton, calling CreateObject prevents the instance from being cached
                // otherwise the container could not guarantee the results of calling GetObject() to other clients.
                TestObject to2 = lof.CreateObject("singleton", typeof(TestObject), null) as TestObject;
                Assert.IsNotNull(to2);
                // no props set
                Assert.AreEqual(0, to2.Age);
                Assert.AreEqual(null, to2.Name);
                // no object postprocessors executed!
                Assert.AreEqual(null, to2.ObjectName);
                Assert.AreEqual(null, to2.ObjectFactory);
                Assert.AreEqual(null, to2.SharedState);

                // a call to GetObject() results in a normally configured instance
                TestObject to3 = lof.GetObject("singleton") as TestObject;
                Assert.IsNotNull(to3);
                // props set
                Assert.AreEqual(27, to3.Age);
                Assert.AreEqual("Bruno", to3.Name);
                // object postprocessors executed!
                Assert.AreEqual("singleton", to3.ObjectName);
                Assert.AreEqual(lof, to3.ObjectFactory);
                Assert.IsNotNull(to3.SharedState);
            }
        }
        /// <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);
            }
        }
        public void CreateObjectWithMixOfNamedAndIndexedAndAutowiredCtorArguments()
        {
            string expectedCompany = "Griffin's Foosball Arcade";
            MutablePropertyValues autoProps = new MutablePropertyValues();
            autoProps.Add(new PropertyValue("Company", expectedCompany));
            RootObjectDefinition autowired = new RootObjectDefinition(typeof(NestedTestObject), autoProps);

            string expectedName = "Bingo";
            int expectedAge = 1023;
            ConstructorArgumentValues values = new ConstructorArgumentValues();
            values.AddNamedArgumentValue("age", expectedAge);
            values.AddIndexedArgumentValue(0, expectedName);
            RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), values, new MutablePropertyValues());
            def.AutowireMode = AutoWiringMode.Constructor;
            DefaultListableObjectFactory fac = new DefaultListableObjectFactory();
            fac.RegisterObjectDefinition("foo", def);
            fac.RegisterObjectDefinition("doctor", autowired);

            ITestObject foo = fac["foo"] as ITestObject;
            Assert.IsNotNull(foo, "Couldn't pull manually registered instance out of the factory.");
            Assert.AreEqual(expectedName, foo.Name, "Dependency 'name' was not resolved an indexed ctor arg.");
            Assert.AreEqual(expectedAge, foo.Age, "Dependency 'age' was not resolved using a named ctor arg.");
            Assert.AreEqual(expectedCompany, foo.Doctor.Company, "Dependency 'doctor.Company' was not resolved using autowiring.");
        }
 /// <summary>
 /// Parse a property element.
 /// </summary>
 /// <param name="name">
 /// The name of the object (definition) associated with the property.
 /// </param>
 /// <param name="properties">
 /// The list of properties associated with the object (definition).
 /// </param>
 /// <param name="element">
 /// The name of the element containing the property definition.
 /// </param>
 /// <param name="parserContext">
 /// The namespace-aware parser.
 /// </param>
 protected void ParsePropertyElement(
     string name, MutablePropertyValues properties, XmlElement element, ParserContext parserContext)
 {
     string propertyName = GetAttributeValue(element, ObjectDefinitionConstants.NameAttribute);
     if (StringUtils.IsNullOrEmpty(propertyName))
     {
         throw new ObjectDefinitionStoreException(
             parserContext.ReaderContext.Resource,
             name,
             "The 'property' element must have a 'name' attribute");
     }
     object val = ParsePropertyValue(element, name, parserContext);
     properties.Add(new PropertyValue(propertyName, val));
 }
        public void CreateObjectWithMixOfIndexedAndTwoNamedSameTypeCtorArguments()
        {
            // this object will be passed in as a named constructor argument
            string expectedCompany = "Griffin's Foosball Arcade";
            MutablePropertyValues autoProps = new MutablePropertyValues();
            autoProps.Add(new PropertyValue("Company", expectedCompany));
            RootObjectDefinition autowired = new RootObjectDefinition(typeof(NestedTestObject), autoProps);

            // this object will be passed in as a named constructor argument
            string expectedLawyersCompany = "Pollack, Pounce, & Pulverise";
            MutablePropertyValues lawyerProps = new MutablePropertyValues();
            lawyerProps.Add(new PropertyValue("Company", expectedLawyersCompany));
            RootObjectDefinition lawyer = new RootObjectDefinition(typeof(NestedTestObject), lawyerProps);

            // this simple string object will be passed in as an indexed constructor argument
            string expectedName = "Bingo";

            // this simple integer object will be passed in as a named constructor argument
            int expectedAge = 1023;

            ConstructorArgumentValues values = new ConstructorArgumentValues();

            // lets mix the order up a little...
            values.AddNamedArgumentValue("age", expectedAge);
            values.AddIndexedArgumentValue(0, expectedName);
            values.AddNamedArgumentValue("doctor", new RuntimeObjectReference("a_doctor"));
            values.AddNamedArgumentValue("lawyer", new RuntimeObjectReference("a_lawyer"));

            RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), values, new MutablePropertyValues());

            DefaultListableObjectFactory fac = new DefaultListableObjectFactory();
            // the object we're attempting to resolve...
            fac.RegisterObjectDefinition("foo", def);
            // the object that will be looked up and passed as a named parameter to a ctor call...
            fac.RegisterObjectDefinition("a_doctor", autowired);
            // another object that will be looked up and passed as a named parameter to a ctor call...
            fac.RegisterObjectDefinition("a_lawyer", lawyer);

            ITestObject foo = fac["foo"] as ITestObject;
            Assert.IsNotNull(foo, "Couldn't pull manually registered instance out of the factory.");
            Assert.AreEqual(expectedName, foo.Name, "Dependency 'name' was not resolved an indexed ctor arg.");
            Assert.AreEqual(expectedAge, foo.Age, "Dependency 'age' was not resolved using a named ctor arg.");
            Assert.AreEqual(expectedCompany, foo.Doctor.Company, "Dependency 'doctor.Company' was not resolved using autowiring.");
            Assert.AreEqual(expectedLawyersCompany, foo.Lawyer.Company, "Dependency 'lawyer.Company' was not resolved using another named ctor arg.");
        }
 /// <summary>
 /// Creates a new instance of the
 /// <see cref="Spring.Objects.Factory.Support.RootWebObjectDefinition"/> class
 /// for an .aspx page, providing property values.
 /// </summary>
 /// <param name="pageName">
 /// Name of the .aspx page to instantiate.
 /// </param>
 /// <param name="properties">
 /// The <see cref="Spring.Objects.MutablePropertyValues"/> to be applied to
 /// a new instance of the object.
 /// </param>
 public RootWebObjectDefinition(
     string pageName,
     MutablePropertyValues properties)
     : base(WebObjectUtils.GetPageType(pageName), null, properties)
 {
     _pageName = WebUtils.CombineVirtualPaths(VirtualEnvironment.CurrentExecutionFilePath, pageName);
 }
        public void SPR_1077()
        {
            DisposableTestObject sing = null;
            using (DefaultListableObjectFactory lof = new DefaultListableObjectFactory())
            {
                RootObjectDefinition singleton
                    = new RootObjectDefinition(typeof(DisposableTestObject));
                MutablePropertyValues sprops = new MutablePropertyValues();
                sprops.Add("name", "Rick");
                singleton.PropertyValues = sprops;
                lof.RegisterObjectDefinition("singleton", singleton);

                RootObjectDefinition prototype
                    = new RootObjectDefinition(typeof(TestObject));
                MutablePropertyValues pprops = new MutablePropertyValues();
                pprops.Add("name", "Jenny");
                // prototype has dependency on a singleton...
                pprops.Add("spouse", new RuntimeObjectReference("singleton"));
                prototype.PropertyValues = pprops;
                prototype.IsSingleton = false;
                lof.RegisterObjectDefinition("prototype", prototype);

                sing = (DisposableTestObject)lof.GetObject("singleton");

                lof.GetObject("prototype");
                lof.GetObject("prototype");
                lof.GetObject("prototype");
                lof.GetObject("prototype");
            }
            Assert.AreEqual(1, sing.NumTimesDisposed);
        }
        public void TestIInstantiationAwareObjectPostProcessorsInterception()
        {
            ProxyingInstantiationAwareObjectPostProcessorStub proc
                = new ProxyingInstantiationAwareObjectPostProcessorStub("TheAgony");

            MutablePropertyValues props = new MutablePropertyValues();
            props.Add("Name", "Rick");
            RootObjectDefinition toBeProxied
                = new RootObjectDefinition(typeof(TestObject), props);

            DefaultListableObjectFactory lof = new DefaultListableObjectFactory();
            lof.AddObjectPostProcessor(proc);
            lof.RegisterObjectDefinition("toBeProxied", toBeProxied);

            object proxy = lof["toBeProxied"];
            Assert.IsNotNull(proxy);
            Assert.AreEqual("TheAgony", proxy);
        }
        public void TestIInstantiationAwareObjectPostProcessorsPassThrough()
        {
            NullInstantiationAwareObjectPostProcessorStub proc
                = new NullInstantiationAwareObjectPostProcessorStub();

            MutablePropertyValues props = new MutablePropertyValues();
            props.Add("Name", "Rick");
            RootObjectDefinition not
                = new RootObjectDefinition(typeof(TestObject), props);

            DefaultListableObjectFactory lof = new DefaultListableObjectFactory();
            lof.AddObjectPostProcessor(proc);
            lof.RegisterObjectDefinition("notToBeProxied", not);

            object foo = lof["notToBeProxied"];
            Assert.IsNotNull(foo);
            Assert.AreEqual(typeof(TestObject), foo.GetType());
            TestObject to = (TestObject)foo;
            Assert.AreEqual("Rick", to.Name);
        }
        public void OverridePropertyExpression()
        {
            StaticApplicationContext ac = new StaticApplicationContext();

            MutablePropertyValues pvs = new MutablePropertyValues();
            pvs.Add("Age", new ExpressionHolder("26+1"));
            ac.RegisterSingleton("tb1", typeof(TestObject), pvs);

            pvs = new MutablePropertyValues();
            pvs.Add("Properties", "<spring-config><add key=\"tb1.Age\" value=\"26-1\"/></spring-config>");
            ac.RegisterSingleton("configurer", typeof(PropertyOverrideConfigurer), pvs);

            ac.Refresh();
            TestObject tb1 = (TestObject)ac.GetObject("tb1");
            Assert.AreEqual(25, tb1.Age);
        }
 public void WithUnresolvablePlaceholder()
 {
     StaticApplicationContext ac = new StaticApplicationContext();
     MutablePropertyValues pvs = new MutablePropertyValues();
     pvs.Add("name", "${ref}");
     ac.RegisterSingleton("tb", typeof (TestObject), pvs);
     ac.RegisterSingleton("configurer", typeof (PropertyPlaceholderConfigurer), null);
     try
     {
         ac.Refresh();
         Assert.Fail("Should have thrown ObjectDefinitionStoreException");
     }
     catch (ObjectDefinitionStoreException ex)
     {
         // expected
         Assert.IsTrue(ex.Message.IndexOf("ref") != -1);
     }
 }