public static object createTypeSetPropertiesAndInvokeMethod(Type tTargetType, String sMethodToInvoke, Dictionary<String, Object> dProperties) { string sFactoryObject = "FactoryObject"; string sInvokeResult = "InvokeResult"; var ctx = new GenericApplicationContext(); // create factory Object, add (if required) its properties to it and register it var rodFactoryObject = new RootObjectDefinition {ObjectType = tTargetType}; if (dProperties != null) foreach (String sProperty in dProperties.Keys) rodFactoryObject.PropertyValues.Add(sProperty, dProperties[sProperty]); ctx.RegisterObjectDefinition(sFactoryObject, rodFactoryObject); // create object to invoke method and register it var rodMethodToInvoke = new RootObjectDefinition { FactoryMethodName = sMethodToInvoke, FactoryObjectName = sFactoryObject }; ctx.RegisterObjectDefinition(sInvokeResult, rodMethodToInvoke); // when we get the rodMethodToInvoke object, the rodFactoryObject will be created return ctx.GetObject(sInvokeResult); }
/// <summary> /// Registers the attribute config processors. /// </summary> /// <param name="registry">The registry.</param> public static void RegisterAttributeConfigProcessors(IObjectDefinitionRegistry registry) { if (!registry.ContainsObjectDefinition(CONFIGURATION_ATTRIBUTE_PROCESSOR_OBJECT_NAME)) { RootObjectDefinition objectDefinition = new RootObjectDefinition(typeof(ConfigurationClassPostProcessor)); RegisterPostProcessor(registry, objectDefinition, CONFIGURATION_ATTRIBUTE_PROCESSOR_OBJECT_NAME); } if (!registry.ContainsObjectDefinition(AUTOWIRED_ATTRIBUTE_PROCESSOR_OBJECT_NAME)) { RootObjectDefinition objectDefinition = new RootObjectDefinition(typeof(AutowiredAttributeObjectPostProcessor)); RegisterPostProcessor(registry, objectDefinition, AUTOWIRED_ATTRIBUTE_PROCESSOR_OBJECT_NAME); } if (!registry.ContainsObjectDefinition(REQUIRED_ATTRIBUTE_PROCESSOR_OBJECT_NAME)) { RootObjectDefinition objectDefinition = new RootObjectDefinition(typeof(RequiredAttributeObjectPostProcessor)); RegisterPostProcessor(registry, objectDefinition, REQUIRED_ATTRIBUTE_PROCESSOR_OBJECT_NAME); } if (!registry.ContainsObjectDefinition(INITDESTROY_ATTRIBUTE_PROCESSOR_OBJECT_NAME)) { RootObjectDefinition objectDefinition = new RootObjectDefinition(typeof(InitDestroyAttributeObjectPostProcessor)); RegisterPostProcessor(registry, objectDefinition, INITDESTROY_ATTRIBUTE_PROCESSOR_OBJECT_NAME); } }
public void Setup() { _applicationContext = new GenericApplicationContext(); var objDef = new RootObjectDefinition(typeof (InitDestroyAttributeObjectPostProcessor)); objDef.Role = ObjectRole.ROLE_INFRASTRUCTURE; _applicationContext.ObjectFactory.RegisterObjectDefinition("InitDestroyAttributeObjectPostProcessor", objDef); objDef = new RootObjectDefinition(typeof(PostContructTestObject1)); _applicationContext.ObjectFactory.RegisterObjectDefinition("PostContructTestObject1", objDef); objDef = new RootObjectDefinition(typeof(PostContructTestObject2)); _applicationContext.ObjectFactory.RegisterObjectDefinition("PostContructTestObject2", objDef); objDef = new RootObjectDefinition(typeof(PostContructTestObject3)); _applicationContext.ObjectFactory.RegisterObjectDefinition("PostContructTestObject3", objDef); objDef = new RootObjectDefinition(typeof(PostContructTestObject4)); objDef.Scope = "prototype"; _applicationContext.ObjectFactory.RegisterObjectDefinition("PostContructTestObject4", objDef); objDef = new RootObjectDefinition(typeof(PostContructTestObject5)); _applicationContext.ObjectFactory.RegisterObjectDefinition("PostContructTestObject5", objDef); objDef = new RootObjectDefinition(typeof(PostContructTestObject1)); objDef.InitMethodName = "Init1"; _applicationContext.ObjectFactory.RegisterObjectDefinition("PostContructTestObject6", objDef); _applicationContext.Refresh(); }
public void InstantiationWithClassName() { RootObjectDefinition def = new RootObjectDefinition( typeof( TestObject ).AssemblyQualifiedName, new ConstructorArgumentValues(), new MutablePropertyValues() ); Assert.IsFalse( def.HasObjectType ); Assert.IsNull( def.ObjectType ); // must bail... }
protected override AbstractObjectDefinition ParseInternal(XmlElement element, ParserContext parserContext) { ObjectDefinitionBuilder builder = BuildObjectDefinition(element, parserContext); ManagedList interceptors = null; XmlElement interceptorsElement = DomUtils.GetChildElementByTagName(element, "interceptors"); if(interceptorsElement != null) { ChannelInterceptorParser interceptorParser = new ChannelInterceptorParser(); interceptors = interceptorParser.ParseInterceptors(interceptorsElement, new ParserContext(parserContext.ParserHelper, builder.RawObjectDefinition)); } if(interceptors == null) { interceptors = new ManagedList(); } string datatypeAttr = element.GetAttribute("datatype"); if(StringUtils.HasText(datatypeAttr)) { string[] datatypes = StringUtils.CommaDelimitedListToStringArray(datatypeAttr); RootObjectDefinition selectorDef = new RootObjectDefinition(); selectorDef.ObjectTypeName = IntegrationNamespaceUtils.SELECTOR_PACKAGE + ".PayloadTypeSelector"; selectorDef.ConstructorArgumentValues.AddGenericArgumentValue(datatypes); string selectorObjectName = parserContext.ReaderContext.RegisterWithGeneratedName(selectorDef); RootObjectDefinition interceptorDef = new RootObjectDefinition(); interceptorDef.ObjectTypeName = IntegrationNamespaceUtils.CHANNEL_INTERCEPTOR_PACKAGE + ".MessageSelectingInterceptor"; interceptorDef.ConstructorArgumentValues.AddGenericArgumentValue(new RuntimeObjectReference(selectorObjectName)); string interceptorObjectName = parserContext.ReaderContext.RegisterWithGeneratedName(interceptorDef); interceptors.Add(new RuntimeObjectReference(interceptorObjectName)); } builder.AddPropertyValue("interceptors", interceptors); return builder.ObjectDefinition; }
public void CanProxyFactoryMethodProducts() { GenericApplicationContext ctx = new GenericApplicationContext(); ctx.ObjectFactory.AddObjectPostProcessor(new DefaultAdvisorAutoProxyCreator()); CapturingAdvice capturingAdvice = new CapturingAdvice(); ctx.ObjectFactory.RegisterSingleton("logging", new DefaultPointcutAdvisor(TruePointcut.True, capturingAdvice)); // register "factory" object RootObjectDefinition rod; rod = new RootObjectDefinition(typeof(TestObjectFactoryObject)); ctx.ObjectFactory.RegisterObjectDefinition("test", rod); // register product, referencing the factory object rod = new RootObjectDefinition(typeof(ITestObject)); rod.FactoryObjectName = "test"; rod.FactoryMethodName = "CreateTestObject"; ctx.ObjectFactory.RegisterObjectDefinition("testProduct", rod); ctx.Refresh(); ITestObjectFactoryObject fo = (ITestObjectFactoryObject) ctx.GetObject("test"); Assert.IsTrue( AopUtils.IsAopProxy(fo) ); Assert.AreEqual("CreateTestObject", ((IMethodInvocation)capturingAdvice.CapturedCalls[0]).Method.Name); capturingAdvice.CapturedCalls.Clear(); ITestObject to = (ITestObject)ctx.GetObject("testProduct"); Assert.IsTrue( AopUtils.IsAopProxy(to) ); Assert.AreEqual("TheName", to.Name); Assert.AreEqual("get_Name", ((IMethodInvocation)capturingAdvice.CapturedCalls[0]).Method.Name); }
public void ChokesOnCircularReferenceToPlaceHolder() { RootObjectDefinition def = new RootObjectDefinition(); def.ObjectType = typeof (TestObject); ConstructorArgumentValues args = new ConstructorArgumentValues(); args.AddNamedArgumentValue("name", "${foo}"); def.ConstructorArgumentValues = args; NameValueCollection properties = new NameValueCollection(); const string expectedName = "ba${foo}r"; properties.Add("foo", expectedName); IConfigurableListableObjectFactory mock = (IConfigurableListableObjectFactory) mocks.CreateMock(typeof (IConfigurableListableObjectFactory)); Expect.Call(mock.GetObjectDefinitionNames()).Return(new string[] {"foo"}); Expect.Call(mock.GetObjectDefinition(null)).IgnoreArguments().Return(def); mocks.ReplayAll(); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.Properties = properties; try { cfg.PostProcessObjectFactory(mock); Assert.Fail("Should have raised an ObjectDefinitionStoreException by this point."); } catch (ObjectDefinitionStoreException) { } mocks.VerifyAll(); }
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 ClearWithDynamicProxies() { CompositionProxyTypeBuilder typeBuilder = new CompositionProxyTypeBuilder(); typeBuilder.TargetType = typeof(TestObject); Type proxyType = typeBuilder.BuildProxyType(); DefaultListableObjectFactory of = new DefaultListableObjectFactory(); RootObjectDefinition od1 = new RootObjectDefinition(proxyType, false); od1.PropertyValues.Add("Name", "Bruno"); of.RegisterObjectDefinition("testObject", od1); GenericApplicationContext ctx1 = new GenericApplicationContext(of); ContextRegistry.RegisterContext(ctx1); ITestObject to1 = ContextRegistry.GetContext().GetObject("testObject") as ITestObject; Assert.IsNotNull(to1); Assert.AreEqual("Bruno", to1.Name); DefaultListableObjectFactory of2 = new DefaultListableObjectFactory(); RootObjectDefinition od2 = new RootObjectDefinition(proxyType, false); od2.PropertyValues.Add("Name", "Baia"); of2.RegisterObjectDefinition("testObject", od2); GenericApplicationContext ctx2 = new GenericApplicationContext(of2); ContextRegistry.Clear(); ITestObject to2 = ctx2.GetObject("testObject") as ITestObject; Assert.IsNotNull(to2); Assert.AreEqual("Baia", to2.Name); }
/// <summary> /// Central template method to actually parse the supplied XmlElement /// into one or more IObjectDefinitions. /// </summary> /// <param name="element">The element that is to be parsed into one or more <see cref="IObjectDefinition"/>s</param> /// <param name="parserContext">The the object encapsulating the current state of the parsing process; /// provides access to a <see cref="IObjectDefinitionRegistry"/></param> /// <returns> /// The primary IObjectDefinition resulting from the parsing of the supplied XmlElement /// </returns> protected override AbstractObjectDefinition ParseInternal(XmlElement element, ParserContext parserContext) { ConfigureAutoProxyCreator(parserContext, element); //Create the TransactionAttributeSource RootObjectDefinition sourceDef = new RootObjectDefinition(typeof(AttributesTransactionAttributeSource)); sourceDef.Role = ObjectRole.ROLE_INFRASTRUCTURE; string sourceName = parserContext.ReaderContext.RegisterWithGeneratedName(sourceDef); //Create the TransactionInterceptor definition. RootObjectDefinition interceptorDefinition = new RootObjectDefinition(typeof(TransactionInterceptor)); interceptorDefinition.Role = ObjectRole.ROLE_INFRASTRUCTURE; RegisterTransactionManager(element, interceptorDefinition); interceptorDefinition.PropertyValues.Add(TxNamespaceUtils.TRANSACTION_ATTRIBUTE_SOURCE, new RuntimeObjectReference(sourceName)); String interceptorName = parserContext.ReaderContext.RegisterWithGeneratedName(interceptorDefinition); // Create the TransactionAttributeSourceAdvisor definition. RootObjectDefinition advisorDef = new RootObjectDefinition(typeof(ObjectFactoryTransactionAttributeSourceAdvisor)); advisorDef.Role = ObjectRole.ROLE_INFRASTRUCTURE; advisorDef.PropertyValues.Add("transactionAttributeSource", new RuntimeObjectReference(sourceName)); advisorDef.PropertyValues.Add("adviceObjectName", interceptorName); if (element.HasAttribute(ORDER)) { advisorDef.PropertyValues.Add(ORDER, GetAttributeValue(element, ORDER)); } return advisorDef; }
private static NamedObjectDefinition Find( string url, string objectName ) { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); RootObjectDefinition rod = new RootObjectDefinition( typeof( Type1 ) ); of.RegisterObjectDefinition( objectName, rod ); return FindWebObjectDefinition( url, of ); }
public void VisitObjectTypeName() { IObjectDefinition od = new RootObjectDefinition(); od.ObjectTypeName = "$Property"; ObjectDefinitionVisitor odv = new ObjectDefinitionVisitor(new ObjectDefinitionVisitor.ResolveHandler(ParseAndResolveVariables)); odv.VisitObjectDefinition(od); Assert.AreEqual("Value", od.ObjectTypeName); }
public void VisitPropertyValues() { IObjectDefinition od = new RootObjectDefinition(); od.PropertyValues.Add("PropertyName", "$Property"); ObjectDefinitionVisitor odv = new ObjectDefinitionVisitor(new ObjectDefinitionVisitor.ResolveHandler(ParseAndResolveVariables)); odv.VisitObjectDefinition(od); Assert.AreEqual("Value", od.PropertyValues.GetPropertyValue("PropertyName").Value); }
/// <summary> /// Registers the attribute config processors. /// </summary> /// <param name="registry">The registry.</param> public static void RegisterAttributeConfigProcessors(IObjectDefinitionRegistry registry) { if (!registry.ContainsObjectDefinition(CONFIGURATION_ATTRIBUTE_PROCESSOR_OBJECT_NAME)) { RootObjectDefinition objectDefinition = new RootObjectDefinition(typeof(ConfigurationClassPostProcessor)); RegisterPostProcessor(registry, objectDefinition, CONFIGURATION_ATTRIBUTE_PROCESSOR_OBJECT_NAME); } //AUTOWIRED_ATTRIBUTE_PROCESSOR_OBJECT_NAME //REQUIRED_ATTRIBUTE_PROCESSOR_OBJECT_NAME }
/// <summary> /// Registers the internal auto proxy creator if necessary. /// </summary> public static void RegisterAutoProxyCreatorIfNecessary(IObjectDefinitionRegistry registry) { AssertUtils.ArgumentNotNull(registry, "registry"); if (!registry.ContainsObjectDefinition(AUTO_PROXY_CREATOR_OBJECT_NAME)) { RootObjectDefinition objectDefinition = new RootObjectDefinition(InfrastructureAutoProxyCreatorType); objectDefinition.Role = ObjectRole.ROLE_INFRASTRUCTURE; objectDefinition.PropertyValues.Add("order", int.MaxValue); registry.RegisterObjectDefinition(AUTO_PROXY_CREATOR_OBJECT_NAME, objectDefinition); } }
/// <summary> /// Instantiate an instance of the object described by the supplied /// <paramref name="definition"/> from the supplied <paramref name="factory"/>. /// </summary> /// <param name="definition"> /// The definition of the object that is to be instantiated. /// </param> /// <param name="name"> /// The name associated with the object definition. The name can be the null /// or zero length string if we're autowiring an object that doesn't belong /// to the supplied <paramref name="factory"/>. /// </param> /// <param name="factory"> /// The owning <see cref="Spring.Objects.Factory.IObjectFactory"/> /// </param> /// <returns> /// An instance of the object described by the supplied /// <paramref name="definition"/> from the supplied <paramref name="factory"/>. /// </returns> public override object Instantiate( RootObjectDefinition definition, string name, IObjectFactory factory) { if (definition is IWebObjectDefinition && ((IWebObjectDefinition) definition).IsPage) { return WebObjectUtils.CreatePageInstance(((IWebObjectDefinition) definition).PageName); } else { return base.Instantiate(definition, name, factory); } }
public void Setup() { _context = new GenericApplicationContext(); var objectDefinition = new RootObjectDefinition(typeof(DestructionPostProcessor)); objectDefinition.Role = ObjectRole.ROLE_INFRASTRUCTURE; _context.ObjectFactory.RegisterObjectDefinition("DestructionPostProcessor", objectDefinition); var objectDef = new RootObjectDefinition(typeof(DestroyTester)); _context.ObjectFactory.RegisterObjectDefinition("DestroyTester", objectDef); _context.Refresh(); }
public void SetUp() { _singletonDefinition = new RootObjectDefinition(typeof (TestObject), AutoWiringMode.No); _singletonDefinitionWithFactory = new RootObjectDefinition(_singletonDefinition); _singletonDefinitionWithFactory.FactoryMethodName = "GetObject"; _singletonDefinitionWithFactory.FactoryObjectName = "TestObjectFactoryDefinition"; _testObjectFactory = new RootObjectDefinition(typeof (TestObjectFactory), AutoWiringMode.No); DefaultListableObjectFactory myFactory = new DefaultListableObjectFactory(); myFactory.RegisterObjectDefinition("SingletonObjectDefinition", SingletonDefinition); myFactory.RegisterObjectDefinition("SingletonDefinitionWithFactory", SingletonDefinitionWithFactory); myFactory.RegisterObjectDefinition("TestObjectFactoryDefinition", TestObjectFactoryDefinition); _factory = myFactory; }
public void ConvertsWriteConcernCorrectly() { DefaultListableObjectFactory factory = new DefaultListableObjectFactory(); factory.RegisterCustomConverter(typeof(WriteConcern), new WriteConcernTypeConverter()); RootObjectDefinition definition = new RootObjectDefinition(typeof(MongoFactoryObject)); definition.PropertyValues.Add("Url", "mongodb://localhost"); definition.PropertyValues.Add("WriteConcern", "Acknowledged"); factory.RegisterObjectDefinition("factory", definition); MongoFactoryObject obj = factory.GetObject<MongoFactoryObject>("&factory"); Assert.That(ReflectionUtils.GetInstanceFieldValue(obj, "_writeConcern"), Is.EqualTo(WriteConcern.Acknowledged)); }
/// <summary> /// Parse the specified XmlElement and register the resulting /// ObjectDefinitions with the <see cref="P:Spring.Objects.Factory.Xml.ParserContext.Registry"/> IObjectDefinitionRegistry /// embedded in the supplied <see cref="T:Spring.Objects.Factory.Xml.ParserContext"/> /// </summary> /// <param name="element">The element to be parsed.</param> /// <param name="parserContext">TThe object encapsulating the current state of the parsing process. /// Provides access to a IObjectDefinitionRegistry</param> /// <returns>The primary object definition.</returns> /// <remarks> /// <p> /// This method is never invoked if the parser is namespace aware /// and was called to process the root node. /// </p> /// </remarks> public IObjectDefinition ParseElement(XmlElement element, ParserContext parserContext) { IObjectDefinitionRegistry registry = parserContext.ReaderContext.Registry; AssertUtils.ArgumentNotNull(registry, "registry"); if (!registry.ContainsObjectDefinition(CONFIGURATION_ATTRIBUTE_PROCESSOR_OBJECT_NAME)) { var objectDefinition = new RootObjectDefinition(ConfigurationClassPostProcessorType); objectDefinition.Role = ObjectRole.ROLE_INFRASTRUCTURE; registry.RegisterObjectDefinition(CONFIGURATION_ATTRIBUTE_PROCESSOR_OBJECT_NAME, objectDefinition); } return null; }
/// <summary> /// Registers the default message converter with the application context. /// </summary> /// <param name="applicationContext">The application context.</param> /// <returns>The name of the message converter to use for lookups with /// <see cref="DefaultMessageQueueFactory"/>. /// </returns> public static string RegisterDefaultMessageConverter(IApplicationContext applicationContext) { //Create a default message converter to use. RootObjectDefinition rod = new RootObjectDefinition(typeof(XmlMessageConverter)); rod.PropertyValues.Add("TargetTypes", new Type[] { typeof(String) }); rod.IsSingleton = false; IConfigurableApplicationContext ctx = (IConfigurableApplicationContext)applicationContext; DefaultListableObjectFactory of = (DefaultListableObjectFactory)ctx.ObjectFactory; string messageConverterObjectName = "__XmlMessageConverter__"; if (!applicationContext.ContainsObjectDefinition(messageConverterObjectName)) { of.RegisterObjectDefinition(messageConverterObjectName, rod); } return messageConverterObjectName; }
/// <summary> /// Create a new DisposableBeanAdapter for the given bean. /// </summary> /// <param name="instance">The bean instance (never <code>null</code>).</param> /// <param name="objectName">Name of the bean.</param> /// <param name="objectDefinition">The merged bean definition.</param> /// <param name="postProcessors">the List of BeanPostProcessors (potentially IDestructionAwareBeanPostProcessor), if any.</param> public DisposableObjectAdapter(object instance, string objectName, RootObjectDefinition objectDefinition, ISet postProcessors) { AssertUtils.ArgumentNotNull(instance, "Disposable object must not be null"); this.instance = instance; this.objectName = objectName; this.invokeDisposableObject = (this.instance is IDisposable); // && !beanDefinition.IsExternallyManagedDestroyMethod("destroy")); if (null == objectDefinition) { return; } InferDestroyMethodIfNecessary(objectDefinition); string definedDestroyMethodName = objectDefinition.DestroyMethodName; if (definedDestroyMethodName != null && !(this.invokeDisposableObject && "Destroy".Equals(definedDestroyMethodName))) // && !beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) { this.destroyMethodName = definedDestroyMethodName; this.destroyMethod = DetermineDestroyMethod(); if (this.destroyMethod == null) { //TODO: add support for Enforcing Destroy Method //if (beanDefinition.IsEnforceDestroyMethod()) { // throw new BeanDefinitionValidationException("Couldn't find a destroy method named '" + // destroyMethodName + "' on bean with name '" + beanName + "'"); //} } else { Type[] paramTypes = ReflectionUtils.GetParameterTypes(this.destroyMethod); if (paramTypes.Length > 1) { throw new ObjectDefinitionValidationException("Method '" + definedDestroyMethodName + "' of object '" + objectName + "' has more than one parameter - not supported as Destroy Method"); } else if (paramTypes.Length == 1 && !(paramTypes[0] == typeof(bool))) { throw new ObjectDefinitionValidationException("Method '" + definedDestroyMethodName + "' of object '" + objectName + "' has a non-boolean parameter - not supported as Destroy Method"); } } } this.objectPostProcessors = FilterPostProcessors(postProcessors); }
public void SunnyDayReplaceMethod() { RootObjectDefinition replacerDef = new RootObjectDefinition(typeof (NewsFeedFactory)); RootObjectDefinition managerDef = new RootObjectDefinition(typeof (ReturnsNullNewsFeedManager)); managerDef.MethodOverrides.Add(new ReplacedMethodOverride("CreateNewsFeed", "replacer")); DefaultListableObjectFactory factory = new DefaultListableObjectFactory(); factory.RegisterObjectDefinition("manager", managerDef); factory.RegisterObjectDefinition("replacer", replacerDef); INewsFeedManager manager = (INewsFeedManager) factory["manager"]; NewsFeed feed1 = manager.CreateNewsFeed(); Assert.IsNotNull(feed1, "The CreateNewsFeed() method is not being replaced."); Assert.AreEqual(NewsFeedFactory.DefaultName, feed1.Name); NewsFeed feed2 = manager.CreateNewsFeed(); // NewsFeedFactory always yields a new NewsFeed (see class definition below)... Assert.IsFalse(ReferenceEquals(feed1, feed2)); }
public void ShareApplicationTemplate() { RootObjectDefinition rod = new RootObjectDefinition(); HttpApplicationConfigurer h1 = new HttpApplicationConfigurer(); h1.ApplicationTemplate = rod; Assert.AreEqual(rod, h1.ApplicationTemplate); // h2 returns same template as h1 HttpApplicationConfigurer h2 = new HttpApplicationConfigurer(); Assert.AreEqual(rod, h2.ApplicationTemplate); Assert.AreEqual(h2.ApplicationTemplate, h1.ApplicationTemplate); // allows overriding rod = new RootObjectDefinition(); h2.ApplicationTemplate = rod; Assert.AreEqual(rod, h1.ApplicationTemplate); }
private void InferDestroyMethodIfNecessary(RootObjectDefinition beanDefinition) { if ("(Inferred)".Equals(beanDefinition.DestroyMethodName)) { try { MethodInfo candidate = ReflectionUtils.GetMethod(instance.GetType(), "Close", null); if (candidate.IsPublic) { beanDefinition.DestroyMethodName = candidate.Name; } } catch (MissingMethodException) { // no candidate destroy method found beanDefinition.DestroyMethodName = null; } } }
public void InstantiationFromOther() { RootObjectDefinition other = new RootObjectDefinition( typeof( TestObject ), AutoWiringMode.Constructor ); other.IsSingleton = false; other.InitMethodName = "Umberto Eco"; other.DestroyMethodName = "Pedulismus"; other.ConstructorArgumentValues = new ConstructorArgumentValues(); other.DependencyCheck = DependencyCheckingMode.Objects; other.DependsOn = new string[] { "Jimmy", "Joyce" }; other.EventHandlerValues = new EventValues(); other.IsAbstract = true; other.IsLazyInit = true; other.FactoryMethodName = "IfINeedYouIllJustUseYourSimpleName"; other.FactoryObjectName = "PerspirationShop"; other.ResourceDescription = "Ohhh"; other.PropertyValues = new MutablePropertyValues(); other.PropertyValues.Add( "Age", 100 ); InstanceEventHandlerValue handler = new InstanceEventHandlerValue( new TestObject(), "Ping" ); handler.EventName = "Bing"; other.EventHandlerValues.AddHandler( handler ); other.ConstructorArgumentValues.AddGenericArgumentValue( "Wulf", "Sternhammer" ); RootObjectDefinition def = new RootObjectDefinition( other ); // ... Assert.AreEqual( typeof( TestObject ), def.ObjectType ); Assert.AreEqual( AutoWiringMode.Constructor, def.AutowireMode ); Assert.IsFalse( def.IsSingleton ); Assert.AreEqual( "Umberto Eco", def.InitMethodName ); Assert.AreEqual( "Pedulismus", def.DestroyMethodName ); Assert.AreEqual( DependencyCheckingMode.Objects, def.DependencyCheck ); Assert.IsTrue( def.IsAbstract ); Assert.IsTrue( def.IsLazyInit ); Assert.AreEqual( "IfINeedYouIllJustUseYourSimpleName", def.FactoryMethodName ); Assert.AreEqual( "PerspirationShop", def.FactoryObjectName ); Assert.AreEqual( "Ohhh", def.ResourceDescription ); Assert.IsTrue( def.HasConstructorArgumentValues ); Assert.AreEqual( other.ConstructorArgumentValues.ArgumentCount, def.ConstructorArgumentValues.ArgumentCount ); Assert.AreEqual( other.PropertyValues.PropertyValues.Count, def.PropertyValues.PropertyValues.Count ); Assert.AreEqual( other.EventHandlerValues.Events.Count, def.EventHandlerValues.Events.Count ); }
public void _TestSetUp() { DefaultListableObjectFactory parentFactory = new DefaultListableObjectFactory(); _factory = new DefaultListableObjectFactory(parentFactory); RootObjectDefinition rodA = new RootObjectDefinition(_expectedtype); RootObjectDefinition rodB = new RootObjectDefinition(_expectedtype); RootObjectDefinition rodC = new RootObjectDefinition(_expectedtype); RootObjectDefinition rod2A = new RootObjectDefinition(_expectedtype); RootObjectDefinition rod2C = new RootObjectDefinition(_expectedtype); _factory.RegisterObjectDefinition("objA", rodA); _factory.RegisterObjectDefinition("objB", rodB); _factory.RegisterObjectDefinition("objC", rodC); parentFactory.RegisterObjectDefinition("obj2A", rod2A); parentFactory.RegisterObjectDefinition("objB", rodB); parentFactory.RegisterObjectDefinition("obj2C", rod2C); }
/// <summary> /// Factory style method for getting concrete /// <see cref="IConfigurableObjectDefinition"/> /// instances. /// </summary> /// /// <remarks>If no parent is specified, a RootObjectDefinition is created, otherwise a /// ChildObjectDefinition.</remarks> /// <param name="typeName">The <see cref="System.Type"/> of the defined object.</param> /// <param name="parent">The name of the parent object definition (if any).</param> /// <param name="domain">The <see cref="System.AppDomain"/> against which any class names /// will be resolved into <see cref="System.Type"/> instances.</param> /// <returns> /// An /// <see cref="IConfigurableObjectDefinition"/> /// instance. /// </returns> public virtual AbstractObjectDefinition CreateObjectDefinition(string typeName, string parent, AppDomain domain) { Type objectType = null; if (StringUtils.HasText(typeName) && domain != null) { try { objectType = TypeResolutionUtils.ResolveType(typeName); } // try later.... catch { } } if (StringUtils.IsNullOrEmpty(parent)) { if (objectType != null) { return new RootObjectDefinition(objectType); } else { RootObjectDefinition rootObjectDefinition = new RootObjectDefinition(); rootObjectDefinition.ObjectTypeName = typeName; return rootObjectDefinition; } } else { if (objectType != null) { ChildObjectDefinition childObjectDefinition = new ChildObjectDefinition(parent); childObjectDefinition.ObjectType = objectType; return childObjectDefinition; } else { ChildObjectDefinition childObjectDefinition = new ChildObjectDefinition(parent); childObjectDefinition.ObjectTypeName = typeName; return childObjectDefinition; } } }
/// <summary> /// Instantiate an instance of the object described by the supplied /// <paramref name="definition"/> from the supplied <paramref name="factory"/>. /// </summary> /// <param name="definition"> /// The definition of the object that is to be instantiated. /// </param> /// <param name="name"> /// The name associated with the object definition. The name can be the null /// or zero length string if we're autowiring an object that doesn't belong /// to the supplied <paramref name="factory"/>. /// </param> /// <param name="factory"> /// The owning <see cref="Spring.Objects.Factory.IObjectFactory"/> /// </param> /// <returns> /// An instance of the object described by the supplied /// <paramref name="definition"/> from the supplied <paramref name="factory"/>. /// </returns> public virtual object Instantiate( RootObjectDefinition definition, string name, IObjectFactory factory) { AssertUtils.ArgumentNotNull(definition, "definition"); AssertUtils.ArgumentNotNull(factory, "factory"); if (log.IsTraceEnabled) log.Trace(string.Format("instantiating object '{0}'", name)); if (definition.HasMethodOverrides) { return InstantiateWithMethodInjection(definition, name, factory); } else { Type objectType = definition.HasObjectType ? definition.ObjectType : TypeResolutionUtils.ResolveType(definition.ObjectTypeName); ConstructorInfo constructor = GetZeroArgConstructorInfo(objectType); return ObjectUtils.InstantiateType(constructor, ObjectUtils.EmptyObjects); } }
/// <summary> /// Parse the specified XmlElement and register the resulting /// ObjectDefinitions with the <see cref="ParserContext.Registry"/> IObjectDefinitionRegistry /// embedded in the supplied <see cref="ParserContext"/> /// </summary> /// <param name="element">The element to be parsed.</param> /// <param name="parserContext">The object encapsulating the current state of the parsing process. /// Provides access to a IObjectDefinitionRegistry</param> /// <returns>The primary object definition.</returns> /// <remarks> /// <p> /// This method is never invoked if the parser is namespace aware /// and was called to process the root node. /// </p> /// </remarks> IObjectDefinition IObjectDefinitionParser.ParseElement(XmlElement element, ParserContext parserContext) { AssertUtils.ArgumentNotNull(parserContext, "parserContext"); string id = element.GetAttribute(ObjectDefinitionConstants.IdAttribute); string unresolvedChannelType = element.GetAttribute(ChannelTypeAttribute); string endpointConfigurationName = element.GetAttribute(EndpointConfigurationNameAttribute); IObjectDefinition channelFactoryDefinition; try { Type channelType = TypeResolutionUtils.ResolveType(unresolvedChannelType); Type channelFactoryType = typeof(ChannelFactoryObject<>).MakeGenericType(new Type[1] { channelType }); channelFactoryDefinition = new RootObjectDefinition(channelFactoryType); } catch { // Try to resolve type later (Can be a type alias) channelFactoryDefinition = new RootObjectDefinition( String.Format("Spring.ServiceModel.ChannelFactoryObject<{0}>, Spring.Services", unresolvedChannelType), new ConstructorArgumentValues(), new MutablePropertyValues()); } if (!StringUtils.HasText(id)) { id = parserContext.ReaderContext.GenerateObjectName(channelFactoryDefinition); } channelFactoryDefinition.ConstructorArgumentValues.AddNamedArgumentValue("endpointConfigurationName", endpointConfigurationName); foreach (PropertyValue pv in base.ParsePropertyElements(id, element, parserContext)) { channelFactoryDefinition.PropertyValues.Add(pv); } parserContext.Registry.RegisterObjectDefinition(id, channelFactoryDefinition); return null; }
/// <summary> /// Gets the constructor instantiation info given the object definition. /// </summary> /// <param name="objectName">Name of the object.</param> /// <param name="rod">The RootObjectDefinition</param> /// <param name="chosenCtors">The explicitly chosen ctors.</param> /// <param name="explicitArgs">The explicit chose ctor args.</param> /// <returns>A ConstructorInstantiationInfo containg the specified constructor in the RootObjectDefinition or /// one based on type matching.</returns> public ConstructorInstantiationInfo GetConstructorInstantiationInfo( string objectName, RootObjectDefinition rod, ConstructorInfo[] chosenCtors, object[] explicitArgs) { ObjectWrapper wrapper = new ObjectWrapper(); ConstructorInfo constructorToUse = null; object[] argsToUse = null; if (explicitArgs != null) { argsToUse = explicitArgs; } else { //TODO performance optmization on cached ctors. } // Need to resolve the constructor. bool autowiring = (chosenCtors != null || rod.ResolvedAutowireMode == AutoWiringMode.Constructor); ConstructorArgumentValues resolvedValues = null; int minNrOfArgs = 0; if (explicitArgs != null) { minNrOfArgs = explicitArgs.Length; } else { ConstructorArgumentValues cargs = rod.ConstructorArgumentValues; resolvedValues = new ConstructorArgumentValues(); minNrOfArgs = ResolveConstructorArguments(objectName, rod, wrapper, cargs, resolvedValues); } // Take specified constructors, if any. ConstructorInfo[] candidates = chosenCtors ?? AutowireUtils.GetConstructors(rod, 0); AutowireUtils.SortConstructors(candidates); int minTypeDiffWeight = int.MaxValue; for (int i = 0; i < candidates.Length; i++) { ConstructorInfo candidate = candidates[i]; Type[] paramTypes = ReflectionUtils.GetParameterTypes(candidate.GetParameters()); if (constructorToUse != null && argsToUse.Length > paramTypes.Length) { // already found greedy constructor that can be satisfied, so // don't look any further, there are only less greedy constructors left... break; } if (paramTypes.Length < minNrOfArgs) { throw new ObjectCreationException(rod.ResourceDescription, objectName, string.Format(CultureInfo.InvariantCulture, "'{0}' constructor arguments specified but no matching constructor found " + "in object '{1}' (hint: specify argument indexes, names, or " + "types to avoid ambiguities).", minNrOfArgs, objectName)); } ArgumentsHolder args; if (resolvedValues != null) { // Try to resolve arguments for current constructor //need to check for null as indicator of no ctor arg match instead of using exceptions for flow //control as in the Java implementation args = CreateArgumentArray( objectName, rod, resolvedValues, wrapper, paramTypes, candidate, autowiring, out var unsatisfiedDependencyExceptionData); if (args == null) { if (i == candidates.Length - 1 && constructorToUse == null) { throw new UnsatisfiedDependencyException(rod.ResourceDescription, objectName, unsatisfiedDependencyExceptionData.ParameterIndex, unsatisfiedDependencyExceptionData.ParameterType, unsatisfiedDependencyExceptionData.ErrorMessage); } // try next constructor... continue; } } else { // Explicit arguments given -> arguments length must match exactly if (paramTypes.Length != explicitArgs.Length) { continue; } args = new ArgumentsHolder(explicitArgs); } int typeDiffWeight = args.GetTypeDifferenceWeight(paramTypes); // Choose this constructor if it represents the closest match. if (typeDiffWeight < minTypeDiffWeight) { constructorToUse = candidate; argsToUse = args.arguments; minTypeDiffWeight = typeDiffWeight; } } if (constructorToUse == null) { throw new ObjectCreationException(rod.ResourceDescription, objectName, "Could not resolve matching constructor."); } return(new ConstructorInstantiationInfo(constructorToUse, argsToUse)); }
/// <summary> /// Create an array of arguments to invoke a constructor or static factory method, /// given the resolved constructor arguments values. /// </summary> /// <remarks>When return value is null the out parameter UnsatisfiedDependencyExceptionData will contain /// information for use in throwing a UnsatisfiedDependencyException by the caller. This avoids using /// exceptions for flow control as in the original implementation.</remarks> private ArgumentsHolder CreateArgumentArray(string objectName, RootObjectDefinition rod, ConstructorArgumentValues resolvedValues, ObjectWrapper wrapper, Type[] paramTypes, MethodBase methodOrCtorInfo, bool autowiring, out UnsatisfiedDependencyExceptionData unsatisfiedDependencyExceptionData) { string methodType = (methodOrCtorInfo is ConstructorInfo) ? "constructor" : "factory method"; unsatisfiedDependencyExceptionData = null; ArgumentsHolder args = new ArgumentsHolder(paramTypes.Length); var usedValueHolders = new HybridSet(); List <string> autowiredObjectNames = null; bool resolveNecessary = false; ParameterInfo[] argTypes = methodOrCtorInfo.GetParameters(); for (int paramIndex = 0; paramIndex < paramTypes.Length; paramIndex++) { Type paramType = paramTypes[paramIndex]; string parameterName = argTypes[paramIndex].Name; // If we couldn't find a direct match and are not supposed to autowire, // let's try the next generic, untyped argument value as fallback: // it could match after type conversion (for example, String -> int). ConstructorArgumentValues.ValueHolder valueHolder = null; if (resolvedValues.GetNamedArgumentValue(parameterName) != null) { valueHolder = resolvedValues.GetArgumentValue(parameterName, paramType, usedValueHolders); } else { valueHolder = resolvedValues.GetArgumentValue(paramIndex, paramType, usedValueHolders); } if (valueHolder == null && !autowiring) { valueHolder = resolvedValues.GetGenericArgumentValue(null, usedValueHolders); } if (valueHolder != null) { // We found a potential match - let's give it a try. // Do not consider the same value definition multiple times! usedValueHolders.Add(valueHolder); args.rawArguments[paramIndex] = valueHolder.Value; try { object originalValue = valueHolder.Value; object convertedValue = TypeConversionUtils.ConvertValueIfNecessary(paramType, originalValue, null); args.arguments[paramIndex] = convertedValue; //? args.preparedArguments[paramIndex] = convertedValue; } catch (TypeMismatchException ex) { //To avoid using exceptions for flow control, this is not a cost in Java as stack trace is lazily created. string errorMessage = String.Format(CultureInfo.InvariantCulture, "Could not convert {0} argument value [{1}] to required type [{2}] : {3}", methodType, valueHolder.Value, paramType, ex.Message); unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage); return(null); } } else { // No explicit match found: we're either supposed to autowire or // have to fail creating an argument array for the given constructor. if (!autowiring) { string errorMessage = String.Format(CultureInfo.InvariantCulture, "Ambiguous {0} argument types - " + "Did you specify the correct object references as {0} arguments?", methodType); unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage); return(null); } try { MethodParameter param = MethodParameter.ForMethodOrConstructor(methodOrCtorInfo, paramIndex); autowiredObjectNames = new List <string>(); object autowiredArgument = ResolveAutoWiredArgument(param, objectName, autowiredObjectNames); args.rawArguments[paramIndex] = autowiredArgument; args.arguments[paramIndex] = autowiredArgument; args.preparedArguments[paramIndex] = new AutowiredArgumentMarker(); resolveNecessary = true; } catch (ObjectsException ex) { unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, ex.Message); return(null); } } } if (log.IsEnabled(LogLevel.Debug) && autowiredObjectNames != null) { for (var i = 0; i < autowiredObjectNames.Count; i++) { string autowiredObjectName = autowiredObjectNames[i]; log.LogDebug( $"Autowiring by type from object name '{objectName}' via {methodType} to object named '{autowiredObjectName}'"); } } return(args); }
public void OverrideFromOther() { RootObjectDefinition rod = new RootObjectDefinition(typeof(TestObject), AutoWiringMode.Constructor); rod.IsSingleton = false; rod.InitMethodName = "Umberto Eco"; rod.DestroyMethodName = "Pedulismus"; rod.ConstructorArgumentValues = new ConstructorArgumentValues(); rod.ConstructorArgumentValues.AddGenericArgumentValue("Wulf", "Sternhammer"); rod.DependencyCheck = DependencyCheckingMode.Objects; rod.DependsOn = new string[] { "Jimmy", "Joyce" }; rod.IsAbstract = true; rod.IsLazyInit = true; rod.FactoryMethodName = "IfINeedYouIllJustUseYourSimpleName"; rod.FactoryObjectName = "PerspirationShop"; rod.ResourceDescription = "Ohhh"; rod.PropertyValues = new MutablePropertyValues(); rod.PropertyValues.Add("Age", 100); rod.EventHandlerValues = new EventValues(); InstanceEventHandlerValue handler = new InstanceEventHandlerValue(new TestObject(), "Ping"); handler.EventName = "Bing"; rod.EventHandlerValues.AddHandler(handler); ChildObjectDefinition cod = new ChildObjectDefinition("parent"); cod.ObjectTypeName = "ChildObjectTypeName"; cod.IsSingleton = true; cod.AutowireMode = AutoWiringMode.ByType; cod.InitMethodName = "InitChild"; cod.DestroyMethodName = "DestroyChild"; cod.ConstructorArgumentValues = new ConstructorArgumentValues(); cod.ConstructorArgumentValues.AddNamedArgumentValue("ctorarg", "ctorarg-value"); cod.DependencyCheck = DependencyCheckingMode.None; cod.DependsOn = new string[] { "Aleks", "Mark" }; cod.IsAbstract = false; cod.IsLazyInit = false; cod.FactoryMethodName = "ChildFactoryMethodName"; cod.FactoryObjectName = "ChildFactoryObjectName"; cod.ResourceDescription = "ChildResourceDescription"; cod.PropertyValues = new MutablePropertyValues(); cod.PropertyValues.Add("Prop1", "Val1"); cod.PropertyValues.Add("Age", 50); cod.EventHandlerValues = new EventValues(); handler = new InstanceEventHandlerValue(new TestObject(), "Pong"); handler.EventName = "Bong"; cod.EventHandlerValues.AddHandler(handler); rod.OverrideFrom(cod); // ... Assert.AreEqual("ChildObjectTypeName", rod.ObjectTypeName); Assert.AreEqual(AutoWiringMode.ByType, rod.AutowireMode); Assert.AreEqual(true, rod.IsSingleton); Assert.AreEqual("InitChild", rod.InitMethodName); Assert.AreEqual("DestroyChild", rod.DestroyMethodName); Assert.AreEqual(DependencyCheckingMode.None, rod.DependencyCheck); Assert.AreEqual(4, rod.DependsOn.Count); Assert.AreEqual(false, rod.IsAbstract); Assert.AreEqual(false, rod.IsLazyInit); Assert.AreEqual("ChildFactoryMethodName", rod.FactoryMethodName); Assert.AreEqual("ChildFactoryObjectName", rod.FactoryObjectName); Assert.AreEqual("ChildResourceDescription", rod.ResourceDescription); Assert.AreEqual(2, rod.ConstructorArgumentValues.ArgumentCount); Assert.AreEqual(2, rod.PropertyValues.PropertyValues.Count); Assert.AreEqual("Val1", rod.PropertyValues.GetPropertyValue("Prop1").Value); Assert.AreEqual(50, rod.PropertyValues.GetPropertyValue("Age").Value); Assert.AreEqual(2, rod.EventHandlerValues.Events.Count); }
/// <summary> /// Ensure that all non-lazy-init singletons are instantiated, also /// considering <see cref="Spring.Objects.Factory.IFactoryObject"/>s. /// </summary> /// <exception cref="Spring.Objects.ObjectsException"> /// If one of the singleton objects could not be created. /// </exception> /// <seealso cref="Spring.Objects.Factory.Config.IConfigurableListableObjectFactory.PreInstantiateSingletons"/> public void PreInstantiateSingletons() { #region Instrumentation if (log.IsDebugEnabled) { log.Debug("Pre-instantiating singletons in factory [" + this + "]"); } #endregion try { int definitionCount = objectDefinitionNames.Count; for (int i = 0; i < definitionCount; i++) { string name = (string)objectDefinitionNames[i]; if (!ContainsSingleton(name) && ContainsObjectDefinition(name)) { RootObjectDefinition definition = GetMergedObjectDefinition(name, false); if (!definition.IsAbstract && definition.IsSingleton && !definition.IsLazyInit) { Type objectType = ResolveObjectType(definition, name); if (objectType != null && typeof(IFactoryObject).IsAssignableFrom(definition.ObjectType)) { IFactoryObject factoryObject = (IFactoryObject)GetObject( ObjectFactoryUtils. BuildFactoryObjectName(name)); if (factoryObject.IsSingleton) { GetObject(name); } } else { GetObject(name); } } } } } catch (ObjectsException) { // destroy already created singletons to avoid dangling resources... try { Dispose(); } catch (Exception ex) { log.Error( "PreInstantiateSingletons failed but couldn't destroy any already-created singletons.", ex); } throw; } }
/// <summary> /// Return the object instances that match the given object /// <see cref="System.Type"/> (including subclasses). /// </summary> /// <param name="type"> /// The <see cref="System.Type"/> (class or interface) to match. /// </param> /// <param name="includeNonSingletons"> /// Whether to include prototype objects too or just singletons (also applies to /// <see cref="Spring.Objects.Factory.IFactoryObject"/>s). /// </param> /// <param name="allowEagerInit"> /// Whether to include <see cref="Spring.Objects.Factory.IFactoryObject"/>s too /// or just normal objects. /// </param> /// <returns> /// An <see cref="System.Collections.IDictionary"/> of the matching objects, /// containing the object names as keys and the corresponding object instances /// as values. /// </returns> /// <exception cref="Spring.Objects.ObjectsException"> /// If any of the objects could not be created. /// </exception> /// <seealso cref="Spring.Objects.Factory.IListableObjectFactory.GetObjectsOfType(Type, bool, bool)"/> protected IList DoGetObjectNamesForType(Type type, bool includeNonSingletons, bool allowEagerInit) { IList result = new ArrayList(); string[] objectNames = GetObjectDefinitionNames(); foreach (string s in objectNames) { string objectName = s; if (!IsAlias(objectName)) { try { RootObjectDefinition mod = GetMergedObjectDefinition(objectName, false); // Only check object definition if it is complete if (!mod.IsAbstract && (allowEagerInit || (mod.HasObjectType || !mod.IsLazyInit /*|| this.AllowEagerTypeLoading*/) && !RequiresEagerInitForType(mod.FactoryObjectName))) { bool isFactoryObject = IsFactoryObject(objectName, mod); bool matchFound = (allowEagerInit || !isFactoryObject || ContainsSingleton(objectName)) && (includeNonSingletons || IsSingleton(objectName)) && IsTypeMatch(objectName, type); if (!matchFound && isFactoryObject) { // in case of a FactoryObject, try to match FactoryObject instance itself next objectName = ObjectFactoryUtils.BuildFactoryObjectName(objectName); matchFound = (includeNonSingletons || mod.IsSingleton) && IsTypeMatch(objectName, type); } if (matchFound) { result.Add(objectName); } } } catch (CannotLoadObjectTypeException ex) { if (allowEagerInit) { throw; } // Probably contains a placeholder; lets ignore it for type matching purposes. if (log.IsDebugEnabled) { log.Debug("Ignoring object class loading failure for object '" + objectName + "'", ex); } } catch (ObjectDefinitionStoreException ex) { if (allowEagerInit) { throw; } // Probably contains a placeholder; lets ignore it for type matching purposes. if (log.IsDebugEnabled) { log.Debug("Ignoring unresolvable metadata in object definition '" + objectName + "'", ex); } } } } // check singletons too, to catch manually registered singletons... string[] singletonNames = GetSingletonNames(); foreach (string s in singletonNames) { string objectName = s; // only check if manually registered... if (!ContainsObjectDefinition(objectName)) { // in the case of an IFactoryObject, match the object created by the IFactoryObject... if (IsFactoryObject(objectName)) { if ((includeNonSingletons || IsSingleton(objectName)) && IsTypeMatch(objectName, type)) { result.Add(objectName); continue; } objectName = ObjectFactoryUtils.BuildFactoryObjectName(objectName); } if (IsTypeMatch(objectName, type)) { result.Add(objectName); } } } return(result); }
/// <summary> /// Check whether the given bean is defined as a <see cref="IFactoryObject"/>. /// </summary> /// <param name="objectName">the name of the object</param> /// <param name="rod">the corresponding object definition</param> protected bool IsFactoryObject(String objectName, RootObjectDefinition rod) { Type objectType = PredictObjectType(objectName, rod); return(objectType != null && typeof(IFactoryObject).IsAssignableFrom(objectType)); }
/// <summary> /// Instantiate an instance of the object described by the supplied /// <paramref name="definition"/> from the supplied <paramref name="factory"/>, /// injecting methods as appropriate. /// </summary> /// <remarks> /// <p> /// The default implementation of this method is to throw a /// <see cref="System.InvalidOperationException"/>. /// </p> /// <p> /// Derived classes can override this method if they can instantiate an object /// with the Method Injection specified in the supplied /// <paramref name="definition"/>. Instantiation should use a no-arg constructor. /// </p> /// </remarks> /// <param name="definition"> /// The definition of the object that is to be instantiated. /// </param> /// <param name="objectName"> /// The name associated with the object definition. The name can be a /// <see lang="null"/> or zero length string if we're autowiring an object that /// doesn't belong to the supplied <paramref name="factory"/>. /// </param> /// <param name="factory"> /// The owning <see cref="Spring.Objects.Factory.IObjectFactory"/> /// </param> /// <returns> /// An instance of the object described by the supplied /// <paramref name="definition"/> from the supplied <paramref name="factory"/>. /// </returns> protected virtual object InstantiateWithMethodInjection( RootObjectDefinition definition, string objectName, IObjectFactory factory) { throw new InvalidOperationException("Method Injection not supported in SimpleInstantiationStrategy"); }
/// <summary> /// Instantiate an object instance using a named factory method. /// </summary> /// <remarks> /// <p> /// The method may be static, if the <paramref name="definition"/> /// parameter specifies a class, rather than a /// <see cref="Spring.Objects.Factory.IFactoryObject"/> instance, or an /// instance variable on a factory object itself configured using Dependency /// Injection. /// </p> /// <p> /// Implementation requires iterating over the static or instance methods /// with the name specified in the supplied <paramref name="definition"/> /// (the method may be overloaded) and trying to match with the parameters. /// We don't have the types attached to constructor args, so trial and error /// is the only way to go here. /// </p> /// </remarks> /// <param name="name"> /// The name associated with the supplied <paramref name="definition"/>. /// </param> /// <param name="definition"> /// The definition describing the instance that is to be instantiated. /// </param> /// <param name="arguments"> /// Any arguments to the factory method that is to be invoked. /// </param> /// <returns> /// The result of the factory method invocation (the instance). /// </returns> public virtual IObjectWrapper InstantiateUsingFactoryMethod(string name, RootObjectDefinition definition, object[] arguments) { ObjectWrapper wrapper = new ObjectWrapper(); Type factoryClass = null; bool isStatic = true; ConstructorArgumentValues cargs = definition.ConstructorArgumentValues; ConstructorArgumentValues resolvedValues = new ConstructorArgumentValues(); int expectedArgCount = 0; // we don't have arguments passed in programmatically, so we need to resolve the // arguments specified in the constructor arguments held in the object definition... if (arguments == null || arguments.Length == 0) { expectedArgCount = cargs.ArgumentCount; ResolveConstructorArguments(name, definition, wrapper, cargs, resolvedValues); } else { // if we have constructor args, don't need to resolve them... expectedArgCount = arguments.Length; } if (StringUtils.HasText(definition.FactoryObjectName)) { // it's an instance method on the factory object's class... factoryClass = objectFactory.GetObject(definition.FactoryObjectName).GetType(); isStatic = false; } else { // it's a static factory method on the object class... factoryClass = definition.ObjectType; } GenericArgumentsHolder genericArgsInfo = new GenericArgumentsHolder(definition.FactoryMethodName); IList <MethodInfo> factoryMethodCandidates = FindMethods(genericArgsInfo.GenericMethodName, expectedArgCount, isStatic, factoryClass); bool autowiring = (definition.AutowireMode == AutoWiringMode.Constructor); // try all matching methods to see if they match the constructor arguments... for (int i = 0; i < factoryMethodCandidates.Count; i++) { MethodInfo factoryMethodCandidate = factoryMethodCandidates[i]; if (genericArgsInfo.ContainsGenericArguments) { string[] unresolvedGenericArgs = genericArgsInfo.GetGenericArguments(); if (factoryMethodCandidate.GetGenericArguments().Length != unresolvedGenericArgs.Length) { continue; } Type[] paramTypes = new Type[unresolvedGenericArgs.Length]; for (int j = 0; j < unresolvedGenericArgs.Length; j++) { paramTypes[j] = TypeResolutionUtils.ResolveType(unresolvedGenericArgs[j]); } factoryMethodCandidate = factoryMethodCandidate.MakeGenericMethod(paramTypes); } if (arguments == null || arguments.Length == 0) { Type[] paramTypes = ReflectionUtils.GetParameterTypes(factoryMethodCandidate.GetParameters()); // try to create the required arguments... UnsatisfiedDependencyExceptionData unsatisfiedDependencyExceptionData = null; ArgumentsHolder args = CreateArgumentArray(name, definition, resolvedValues, wrapper, paramTypes, factoryMethodCandidate, autowiring, out unsatisfiedDependencyExceptionData); if (args == null) { arguments = null; // if we failed to match this method, keep // trying new overloaded factory methods... continue; } else { arguments = args.arguments; } } // if we get here, we found a usable candidate factory method - check, if arguments match //arguments = (arguments.Length == 0 ? null : arguments); if (ReflectionUtils.GetMethodByArgumentValues(new MethodInfo[] { factoryMethodCandidate }, arguments) == null) { continue; } object objectInstance = instantiationStrategy.Instantiate(definition, name, objectFactory, factoryMethodCandidate, arguments); wrapper.WrappedInstance = objectInstance; if (log.IsEnabled(LogLevel.Debug)) { log.LogDebug(string.Format(CultureInfo.InvariantCulture, "Object '{0}' instantiated via factory method [{1}].", name, factoryMethodCandidate)); } return(wrapper); } // if we get here, we didn't match any method... throw new ObjectDefinitionStoreException( string.Format(CultureInfo.InvariantCulture, "Cannot find matching factory method '{0} on Type [{1}].", definition.FactoryMethodName, factoryClass)); }