From 0c5c4b37b5f05cb8d3ff6ab3cf9f0e6761857ef9 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Thu, 11 Oct 2018 20:18:02 +0300 Subject: [PATCH] #164 improve performance a bit * faster data structure access * less memory allocations --- .../AdvisorAdapterRegistrationManager.cs | 2 +- .../Aop/Framework/AdvisedSupport.cs | 2 +- .../CompositionAopProxyTypeBuilder.cs | 2 +- .../Aop/Framework/ProxyFactoryObject.cs | 143 ++++---- .../Spring.Core/Collections/DictionarySet.cs | 90 ++--- .../Collections/SynchronizedHashtable.cs | 24 -- .../ConfigurationClassPostProcessor.cs | 9 +- .../GenericApplicationContextExtensions.cs | 5 +- .../Support/AbstractApplicationContext.cs | 329 ++++-------------- .../ApplicationContextAwareProcessor.cs | 23 +- .../Context/Support/ContextRegistry.cs | 50 +-- .../Spring.Core/Core/IPriorityOrdered.cs | 2 - .../AutowiredAttributeObjectPostProcessor.cs | 13 +- .../Config/ConstructorArgumentValues.cs | 230 ++++++------ .../Objects/Factory/Config/EventValues.cs | 89 ++--- .../Config/IAutowireCapableObjectFactory.cs | 231 ++++++------ .../Factory/Config/IObjectDefinition.cs | 4 +- .../Factory/Config/IObjectPostProcessor.cs | 2 +- ...ntiationAwareObjectPostProcessorAdapter.cs | 18 +- .../Factory/Config/ObjectDefinitionVisitor.cs | 139 ++++---- ...rtInstantiationAwareObjectPostProcessor.cs | 2 +- .../Objects/Factory/IListableObjectFactory.cs | 2 +- .../Objects/Factory/IObjectFactory.cs | 2 +- .../Objects/Factory/ObjectFactoryUtils.cs | 39 +-- .../AbstractAutowireCapableObjectFactory.cs | 163 ++++----- .../Support/AbstractObjectDefinition.cs | 278 +++++++-------- .../Factory/Support/AbstractObjectFactory.cs | 271 ++++++--------- .../Factory/Support/ChildObjectDefinition.cs | 2 +- .../Factory/Support/ConstructorResolver.cs | 55 +-- .../Support/DefaultListableObjectFactory.cs | 42 +-- .../Support/DisposableObjectAdapter.cs | 7 +- .../Support/IConfigurableObjectDefinition.cs | 4 +- .../Objects/Factory/Support/MethodOverride.cs | 2 +- .../Factory/Support/MethodOverrides.cs | 106 +++--- .../Support/ObjectDefinitionBuilder.cs | 120 +++---- .../Support/ObjectDefinitionReaderUtils.cs | 4 +- .../Support/ObjectDefinitionValueResolver.cs | 2 +- .../Factory/Support/RootObjectDefinition.cs | 9 +- .../Factory/Xml/ObjectDefinitionConstants.cs | 2 +- .../Spring.Core/Objects/IPropertyValues.cs | 67 ++-- .../Objects/MutablePropertyValues.cs | 184 +++++----- .../Proxy/AbstractProxyTypeBuilder.cs | 2 +- src/Spring/Spring.Core/Util/ArrayUtils.cs | 18 +- src/Spring/Spring.Core/Util/AssertUtils.cs | 164 ++++----- .../Spring.Core/Util/CollectionUtils.cs | 2 +- .../Spring.Core/Util/ConfigurationUtils.cs | 45 +-- src/Spring/Spring.Core/Util/ObjectUtils.cs | 57 ++- src/Spring/Spring.Core/Util/StringUtils.cs | 58 +-- .../Data/Core/RowMapperResultSetExtractor.cs | 44 +-- .../Data/Generic/NamedResultSetProcessor.cs | 32 +- .../Data/Objects/Generic/StoredProcedure.cs | 63 +--- .../Data/Objects/StoredProcedure.cs | 37 +- .../Data/Support/NamedResultSetProcessor.cs | 31 +- .../Config/TxAdviceObjectDefinitionParser.cs | 10 +- ...tractFallbackTransactionAttributeSource.cs | 43 +-- .../AttributesTransactionAttributeSource.cs | 3 +- .../RuleBasedTransactionAttribute.cs | 12 +- .../Nms/Connections/CachedSession.cs | 215 +++++------- .../Connections/CachingConnectionFactory.cs | 85 ++--- .../Nms/Connections/NmsResourceHolder.cs | 79 ++--- .../Scheduling/Quartz/SchedulerAccessor.cs | 4 +- .../Support/RootWebObjectDefinition.cs | 4 +- .../Support/RootObjectDefinitionTests.cs | 2 +- ...supportedObjectDefinitionImplementation.cs | 2 +- .../Xml/XmlListableObjectFactoryTests.cs | 2 +- .../Factory/Xml/XmlObjectCollectionTests.cs | 6 +- .../Factory/Xml/XmlObjectFactoryTests.cs | 28 +- .../Objects/MutablePropertyValuesTests.cs | 8 +- .../RuleBasedTransactionAttributeTests.cs | 101 +++--- .../Nms/Connections/CachedSessionTests.cs | 3 +- 70 files changed, 1577 insertions(+), 2353 deletions(-) diff --git a/src/Spring/Spring.Aop/Aop/Framework/Adapter/AdvisorAdapterRegistrationManager.cs b/src/Spring/Spring.Aop/Aop/Framework/Adapter/AdvisorAdapterRegistrationManager.cs index 11469052..b68b51ed 100644 --- a/src/Spring/Spring.Aop/Aop/Framework/Adapter/AdvisorAdapterRegistrationManager.cs +++ b/src/Spring/Spring.Aop/Aop/Framework/Adapter/AdvisorAdapterRegistrationManager.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Aop/Aop/Framework/AdvisedSupport.cs b/src/Spring/Spring.Aop/Aop/Framework/AdvisedSupport.cs index e0902bc8..cdb91435 100644 --- a/src/Spring/Spring.Aop/Aop/Framework/AdvisedSupport.cs +++ b/src/Spring/Spring.Aop/Aop/Framework/AdvisedSupport.cs @@ -1,5 +1,5 @@ /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Aop/Aop/Framework/DynamicProxy/CompositionAopProxyTypeBuilder.cs b/src/Spring/Spring.Aop/Aop/Framework/DynamicProxy/CompositionAopProxyTypeBuilder.cs index 1e52759a..8849464d 100644 --- a/src/Spring/Spring.Aop/Aop/Framework/DynamicProxy/CompositionAopProxyTypeBuilder.cs +++ b/src/Spring/Spring.Aop/Aop/Framework/DynamicProxy/CompositionAopProxyTypeBuilder.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Aop/Aop/Framework/ProxyFactoryObject.cs b/src/Spring/Spring.Aop/Aop/Framework/ProxyFactoryObject.cs index d8f0f876..5a49785b 100644 --- a/src/Spring/Spring.Aop/Aop/Framework/ProxyFactoryObject.cs +++ b/src/Spring/Spring.Aop/Aop/Framework/ProxyFactoryObject.cs @@ -1,5 +1,5 @@ /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -206,7 +206,7 @@ namespace Spring.Aop.Framework set { // defer freezing this config until the first proxy gets created - this.freezeProxy = value; + freezeProxy = value; } } @@ -262,7 +262,7 @@ namespace Spring.Aop.Framework /// public virtual string TargetName { - set { this.targetName = value; } + set { targetName = value; } } /// @@ -286,7 +286,7 @@ namespace Spring.Aop.Framework /// public virtual string[] InterceptorNames { - set { this.interceptorNames = value; } + set { interceptorNames = value; } } /// @@ -306,7 +306,7 @@ namespace Spring.Aop.Framework /// public virtual string[] IntroductionNames { - set { this.introductionNames = value; } + set { introductionNames = value; } } /// @@ -314,8 +314,8 @@ namespace Spring.Aop.Framework /// public ProxyFactoryObject() { - this.advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.Instance; - this.singleton = true; + advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.Instance; + singleton = true; } /// @@ -335,7 +335,7 @@ namespace Spring.Aop.Framework { set { - this.objectFactory = value; + objectFactory = value; } } @@ -357,20 +357,20 @@ namespace Spring.Aop.Framework /// public virtual object GetObject() { - lock (this.SyncRoot) + lock (SyncRoot) { - if (!this.initialized) + if (!initialized) { Initialize(); - this.initialized = true; + initialized = true; } - if (this.IsSingleton) + if (IsSingleton) { return SingletonInstance; } - if (this.targetName == null) + if (targetName == null) { logger.Warn("Using non-singleton proxies with singleton targets is often undesirable. " + "Enable prototype proxies by setting the 'targetName' property."); @@ -395,19 +395,19 @@ namespace Spring.Aop.Framework get { // TODO (EE): sync with Java - lock (this.SyncRoot) + lock (SyncRoot) { - if (this.singletonInstance != null) + if (singletonInstance != null) { - return this.singletonInstance.GetType(); + return singletonInstance.GetType(); } else if (Interfaces.Count == 1) { return Interfaces[0]; } - else if (this.targetName != null && this.objectFactory != null) + else if (targetName != null && objectFactory != null) { - return this.objectFactory.GetType(this.targetName); + return objectFactory.GetType(targetName); } else { @@ -422,21 +422,21 @@ namespace Spring.Aop.Framework /// public virtual bool IsSingleton { - get { return this.singleton; } - set { this.singleton = value; } + get { return singleton; } + set { singleton = value; } } private object SingletonInstance { get { - if (this.singletonInstance == null) + if (singletonInstance == null) { - this.TargetSource = FreshTargetSource(); - this.singletonInstance = CreateAopProxy().GetProxy(); - base.IsFrozen = this.freezeProxy; // freeze after creating proxy to allow for interface autodetection + TargetSource = FreshTargetSource(); + singletonInstance = CreateAopProxy().GetProxy(); + base.IsFrozen = freezeProxy; // freeze after creating proxy to allow for interface autodetection } - return this.singletonInstance; + return singletonInstance; } } @@ -463,7 +463,7 @@ namespace Spring.Aop.Framework } object generatedProxy = copy.CreateAopProxy().GetProxy(); - base.IsFrozen = this.freezeProxy; // freeze after creating proxy to allow for interface autodetection + base.IsFrozen = freezeProxy; // freeze after creating proxy to allow for interface autodetection return generatedProxy; } @@ -474,7 +474,7 @@ namespace Spring.Aop.Framework { if (logger.IsDebugEnabled) { - logger.Debug(string.Format("Initialize: begin configure target, interceptors and introductions for {0}[{1}]", this.GetType().Name, this.GetHashCode())); + logger.Debug(string.Format("Initialize: begin configure target, interceptors and introductions for {0}[{1}]", GetType().Name, GetHashCode())); } InitializeAdvisorChain(); @@ -482,7 +482,7 @@ namespace Spring.Aop.Framework if (logger.IsDebugEnabled) { - logger.Debug(string.Format("Initialize: completed configuration for {0}[{1}]: {2}", this.GetType().Name, this.GetHashCode(), this.ToProxyConfigString())); + logger.Debug(string.Format("Initialize: completed configuration for {0}[{1}]: {2}", GetType().Name, GetHashCode(), ToProxyConfigString())); } } @@ -494,7 +494,7 @@ namespace Spring.Aop.Framework /// private void InitializeAdvisorChain() { - if (ObjectUtils.IsEmpty(this.interceptorNames)) + if (ObjectUtils.IsEmpty(interceptorNames)) { return; } @@ -502,16 +502,16 @@ namespace Spring.Aop.Framework CheckInterceptorNames(); // Globals can't be last unless we specified a targetSource using the property... - if (this.interceptorNames[this.interceptorNames.Length - 1] != null - && this.interceptorNames[this.interceptorNames.Length - 1].EndsWith(GlobalInterceptorSuffix) - && this.targetName == null - && this.TargetSource == EmptyTargetSource.Empty) + if (interceptorNames[interceptorNames.Length - 1] != null + && interceptorNames[interceptorNames.Length - 1].EndsWith(GlobalInterceptorSuffix) + && targetName == null + && TargetSource == EmptyTargetSource.Empty) { throw new AopConfigException("Target required after globals"); } // materialize interceptor chain from object names... - foreach (string name in this.interceptorNames) + foreach (string name in interceptorNames) { if (name == null) { @@ -520,7 +520,7 @@ namespace Spring.Aop.Framework if (name.EndsWith(GlobalInterceptorSuffix)) { - IListableObjectFactory lof = this.objectFactory as IListableObjectFactory; + IListableObjectFactory lof = objectFactory as IListableObjectFactory; if (lof == null) { throw new AopConfigException("Can only use global advisors or interceptors in conjunction with an IListableObjectFactory."); @@ -543,9 +543,9 @@ namespace Spring.Aop.Framework // If we get here, we need to add a named interceptor. // We must check if it's a singleton or prototype. object advice; - if (this.IsSingleton || this.objectFactory.IsSingleton(name)) + if (IsSingleton || objectFactory.IsSingleton(name)) { - advice = this.objectFactory.GetObject(name); + advice = objectFactory.GetObject(name); AssertUtils.ArgumentNotNull(advice, "advice", "object factory returned a null object"); } else @@ -592,7 +592,7 @@ namespace Spring.Aop.Framework private bool IsNamedObjectAnAdvisorOrAdvice(string name) { - Type namedObjectType = this.objectFactory.GetType(name); + Type namedObjectType = objectFactory.GetType(name); if (namedObjectType != null) { return typeof(IAdvisors).IsAssignableFrom(namedObjectType) @@ -669,13 +669,13 @@ namespace Spring.Aop.Framework /// private void InitializeIntroductionChain() { - if (ObjectUtils.IsEmpty(this.introductionNames)) + if (ObjectUtils.IsEmpty(introductionNames)) { return; } // Materialize introductions from object names... - foreach (string name in this.introductionNames) + foreach (string name in introductionNames) { if (name == null) { @@ -689,19 +689,19 @@ namespace Spring.Aop.Framework if (name.EndsWith(GlobalInterceptorSuffix)) { - if (!(this.objectFactory is IListableObjectFactory)) + if (!(objectFactory is IListableObjectFactory)) { throw new AopConfigException("Can only use global introductions with a ListableObjectFactory"); } - AddGlobalIntroduction((IListableObjectFactory)this.objectFactory, name.Substring(0, (name.Length - GlobalInterceptorSuffix.Length))); + AddGlobalIntroduction((IListableObjectFactory)objectFactory, name.Substring(0, (name.Length - GlobalInterceptorSuffix.Length))); } else { // add a named introduction object introduction; - if (this.IsSingleton || this.objectFactory.IsSingleton(name)) + if (IsSingleton || objectFactory.IsSingleton(name)) { - introduction = this.objectFactory.GetObject(name); + introduction = objectFactory.GetObject(name); AssertUtils.ArgumentNotNull(introduction, "introduction", "object factory returned a null object"); } else @@ -722,7 +722,7 @@ namespace Spring.Aop.Framework ObjectFactoryUtils.ObjectNamesForTypeIncludingAncestors(objectFactory, typeof(IAdvisor)); IList globalIntroductionNames = ObjectFactoryUtils.ObjectNamesForTypeIncludingAncestors(objectFactory, typeof(IAdvice)); - ArrayList objects = new ArrayList(); + List objects = new List(); Dictionary names = new Dictionary(); for (int i = 0; i < globalAspectNames.Count; i++) @@ -771,8 +771,9 @@ namespace Spring.Aop.Framework } } objects.Sort(new OrderComparator()); - foreach (object obj in objects) + for (var i = 0; i < objects.Count; i++) { + object obj = objects[i]; string name = names[obj]; AddIntroductionOnChainCreation(obj, name); } @@ -787,7 +788,7 @@ namespace Spring.Aop.Framework /// object name from which we obtained this object in our owning object factory private void AddIntroductionOnChainCreation(object introduction, string name) { - logger.Debug(string.Format("Adding introduction with name '{0}'", name)); + logger.Debug($"Adding introduction with name '{name}'"); IIntroductionAdvisor advisor = NamedObjectToIntroduction(introduction); AddIntroduction(advisor); } @@ -797,24 +798,24 @@ namespace Spring.Aop.Framework /// private ITargetSource FreshTargetSource() { - if (StringUtils.IsNullOrEmpty(this.targetName)) + if (StringUtils.IsNullOrEmpty(targetName)) { if (logger.IsDebugEnabled) { logger.Debug("Not Refreshing TargetSource: No target name specified"); } - return this.TargetSource; + return TargetSource; } - AssertUtils.ArgumentNotNull(this.objectFactory, "ObjectFactory"); + AssertUtils.ArgumentNotNull(objectFactory, "ObjectFactory"); if (logger.IsDebugEnabled) { - logger.Debug("Refreshing TargetSource with name '" + this.targetName + "'"); + logger.Debug("Refreshing TargetSource with name '" + targetName + "'"); } - object target = this.objectFactory.GetObject(this.targetName); + object target = objectFactory.GetObject(targetName); ITargetSource targetSource = NamedObjectToTargetSource(target); return targetSource; } @@ -837,9 +838,9 @@ namespace Spring.Aop.Framework logger.Debug(string.Format("Refreshing advisor '{0}'", pa.ObjectName)); } - AssertUtils.ArgumentNotNull(this.objectFactory, "ObjectFactory"); + AssertUtils.ArgumentNotNull(objectFactory, "ObjectFactory"); - object advisorObject = this.objectFactory.GetObject(pa.ObjectName); + object advisorObject = objectFactory.GetObject(pa.ObjectName); IAdvisor freshAdvisor = NamedObjectToAdvisor(advisorObject); freshAdvisors.Add(freshAdvisor); } @@ -869,9 +870,9 @@ namespace Spring.Aop.Framework logger.Debug(string.Format("Refreshing introduction '{0}'", pa.ObjectName)); } - AssertUtils.ArgumentNotNull(this.objectFactory, "ObjectFactory"); + AssertUtils.ArgumentNotNull(objectFactory, "ObjectFactory"); - object introductionObject = this.objectFactory.GetObject(pa.ObjectName); + object introductionObject = objectFactory.GetObject(pa.ObjectName); IIntroductionAdvisor freshIntroduction = NamedObjectToIntroduction(introductionObject); freshIntroductions.Add(freshIntroduction); } @@ -939,7 +940,7 @@ namespace Spring.Aop.Framework protected override void InterfacesChanged() { logger.Info("Implemented interfaces have changed; reseting singleton instance"); - this.singletonInstance = null; + singletonInstance = null; base.InterfacesChanged(); } @@ -948,7 +949,7 @@ namespace Spring.Aop.Framework /// protected override string ToProxyConfigStringInternal() { - return string.Format("{0}\ntargetName={1}", base.ToProxyConfigStringInternal(), this.targetName); + return string.Format("{0}\ntargetName={1}", base.ToProxyConfigStringInternal(), targetName); } /// @@ -957,10 +958,10 @@ namespace Spring.Aop.Framework /// private void CheckInterceptorNames() { - if (!ObjectUtils.IsEmpty(this.interceptorNames)) + if (!ObjectUtils.IsEmpty(interceptorNames)) { - String finalName = this.interceptorNames[this.interceptorNames.Length - 1]; - if (finalName != null && this.targetName == null && this.TargetSource == EmptyTargetSource.Empty) + String finalName = interceptorNames[interceptorNames.Length - 1]; + if (finalName != null && targetName == null && TargetSource == EmptyTargetSource.Empty) { // The last name in the chain may be an Advisor/Advice or a target/TargetSource. // Unfortunately we don't know; we must look at type of the bean. @@ -968,14 +969,14 @@ namespace Spring.Aop.Framework && !IsNamedObjectAnAdvisorOrAdvice(finalName)) { // The target isn't an interceptor. - this.targetName = finalName; + targetName = finalName; if (logger.IsDebugEnabled) { logger.Debug(string.Format("Object with name '{0}' concluding interceptor chain is not an advisor class: treating it as a target or TargetSource", finalName)); } - String[] newNames = new String[this.interceptorNames.Length - 1]; - Array.Copy(this.interceptorNames, 0, newNames, 0, newNames.Length); - this.interceptorNames = newNames; + String[] newNames = new String[interceptorNames.Length - 1]; + Array.Copy(interceptorNames, 0, newNames, 0, newNames.Length); + interceptorNames = newNames; } } } @@ -995,32 +996,32 @@ namespace Spring.Aop.Framework public PrototypePlaceholder(string objectName) { this.objectName = objectName; - this.message = "Placeholder for prototype Advisor/Advice/Introduction with bean name '" + objectName + "'"; + message = "Placeholder for prototype Advisor/Advice/Introduction with bean name '" + objectName + "'"; } public bool IsPerInstance { - get { throw new NotSupportedException("Cannot invoke methods: " + this.message); } + get { throw new NotSupportedException("Cannot invoke methods: " + message); } } public IAdvice Advice { - get { throw new NotSupportedException("Cannot invoke methods: " + this.message); } + get { throw new NotSupportedException("Cannot invoke methods: " + message); } } public ITypeFilter TypeFilter { - get { throw new NotSupportedException("Cannot invoke methods: " + this.message); } + get { throw new NotSupportedException("Cannot invoke methods: " + message); } } public Type[] Interfaces { - get { throw new NotSupportedException("Cannot invoke methods: " + this.message); } + get { throw new NotSupportedException("Cannot invoke methods: " + message); } } public void ValidateInterfaces() { - throw new NotSupportedException("Cannot invoke methods: " + this.message); + throw new NotSupportedException("Cannot invoke methods: " + message); } } } diff --git a/src/Spring/Spring.Core/Collections/DictionarySet.cs b/src/Spring/Spring.Core/Collections/DictionarySet.cs index ee9373c7..f68ee4b7 100644 --- a/src/Spring/Spring.Core/Collections/DictionarySet.cs +++ b/src/Spring/Spring.Core/Collections/DictionarySet.cs @@ -1,9 +1,7 @@ -/* Copyright © 2002-2011 by Aidant Systems, Inc., and by Jason Smith. */ - -#region License +/* Copyright © 2002-2011 by Aidant Systems, Inc., and by Jason Smith. */ /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,15 +16,9 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Collections; -#endregion - namespace Spring.Collections { /// @@ -87,8 +79,8 @@ namespace Spring.Collections /// protected IDictionary InternalDictionary { - get { return _internalDictionary; } - set { _internalDictionary = value; } + get => _internalDictionary; + set => _internalDictionary = value; } /// @@ -99,10 +91,7 @@ namespace Spring.Collections /// There is a single instance of this object globally, used for all /// s. /// - protected static object Placeholder - { - get { return PlaceholderObject; } - } + protected static object Placeholder => PlaceholderObject; /// /// Adds the specified element to this set if it is not already present. @@ -115,14 +104,14 @@ namespace Spring.Collections public override bool Add(object element) { element = MaskNull(element); - if (InternalDictionary[element] != null) + if (_internalDictionary[element] != null) { return false; } //The object we are adding is just a placeholder. The thing we are //really concerned with is 'o', the key. - InternalDictionary.Add(element, PlaceholderObject); + _internalDictionary.Add(element, PlaceholderObject); return true; } @@ -140,17 +129,17 @@ namespace Spring.Collections bool changed = false; foreach (object o in collection) { - changed |= this.Add(o); + changed |= Add(o); } return changed; } - + /// /// Removes all objects from this set. /// public override void Clear() { - InternalDictionary.Clear(); + _internalDictionary.Clear(); } /// @@ -164,7 +153,7 @@ namespace Spring.Collections public override bool Contains(object element) { element = MaskNull(element); - return InternalDictionary[element] != null; + return _internalDictionary[element] != null; } /// @@ -185,7 +174,7 @@ namespace Spring.Collections } foreach (object o in collection) { - if (!this.Contains(MaskNull(o))) + if (!Contains(MaskNull(o))) { return false; } @@ -196,10 +185,7 @@ namespace Spring.Collections /// /// Returns if this set contains no elements. /// - public override bool IsEmpty - { - get { return InternalDictionary.Count == 0; } - } + public override bool IsEmpty => _internalDictionary.Count == 0; /// /// Removes the specified element from the set. @@ -211,10 +197,10 @@ namespace Spring.Collections public override bool Remove(object element) { element = MaskNull(element); - bool contained = this.Contains(element); + bool contained = Contains(element); if (contained) { - InternalDictionary.Remove(element); + _internalDictionary.Remove(element); } return contained; } @@ -233,7 +219,7 @@ namespace Spring.Collections bool changed = false; foreach (object o in collection) { - changed |= this.Remove(o); + changed |= Remove(o); } return changed; } @@ -267,7 +253,7 @@ namespace Spring.Collections removeSet.Add(o); } } - return this.RemoveAll(removeSet); + return RemoveAll(removeSet); } /// @@ -298,10 +284,7 @@ namespace Spring.Collections /// /// The number of elements currently contained in this collection. /// - public override int Count - { - get { return InternalDictionary.Count; } - } + public override int Count => _internalDictionary.Count; /// /// Returns if the @@ -309,10 +292,7 @@ namespace Spring.Collections /// threads. /// /// - public override bool IsSynchronized - { - get { return false; } - } + public override bool IsSynchronized => false; /// /// An object that can be used to synchronize this collection to make @@ -323,10 +303,7 @@ namespace Spring.Collections /// it thread-safe. /// /// - public override object SyncRoot - { - get { return InternalDictionary.SyncRoot; } - } + public override object SyncRoot => _internalDictionary.SyncRoot; /// /// Gets an enumerator for the elements in the @@ -338,12 +315,14 @@ namespace Spring.Collections /// public override IEnumerator GetEnumerator() { - return new DictionarySetEnumerator(InternalDictionary.Keys.GetEnumerator()); + return new DictionarySetEnumerator(_internalDictionary.Keys.GetEnumerator()); } + + private static object MaskNull(object key) { - return key == null ? NullPlaceHolderKey : key; + return key ?? NullPlaceHolderKey; } private static object UnmaskNull(object key) @@ -351,41 +330,26 @@ namespace Spring.Collections return key == NullPlaceHolderKey ? null : key; } - #region Inner Class : DictionarySetEnumerator - - private sealed class DictionarySetEnumerator : IEnumerator + private struct DictionarySetEnumerator : IEnumerator { - #region Constructor (s) / Destructor - public DictionarySetEnumerator(IEnumerator enumerator) { _enumerator = enumerator; } - #endregion - - #region IEnumerator Members - public void Reset() { _enumerator.Reset(); } - public object Current - { - get { return UnmaskNull(_enumerator.Current); } - } + public object Current => UnmaskNull(_enumerator.Current); public bool MoveNext() { return _enumerator.MoveNext(); } - #endregion - - private IEnumerator _enumerator; + private readonly IEnumerator _enumerator; } - - #endregion } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Collections/SynchronizedHashtable.cs b/src/Spring/Spring.Core/Collections/SynchronizedHashtable.cs index d9fa715b..a239e06e 100644 --- a/src/Spring/Spring.Core/Collections/SynchronizedHashtable.cs +++ b/src/Spring/Spring.Core/Collections/SynchronizedHashtable.cs @@ -1,5 +1,3 @@ -#region License - /* * Copyright 2002-2010 the original author or authors. * @@ -16,8 +14,6 @@ * limitations under the License. */ -#endregion - using System; using System.Collections; using System.Collections.Specialized; @@ -51,8 +47,6 @@ namespace Spring.Collections private readonly bool _ignoreCase; private readonly Hashtable _table; - #region Constructors - /// /// Initializes a new instance of /// @@ -99,10 +93,6 @@ namespace Spring.Collections return new SynchronizedHashtable(other); } - #endregion - - #region Properties - /// ///Gets a value indicating whether the object is read-only. /// @@ -210,10 +200,6 @@ namespace Spring.Collections } } - #endregion - - #region Methods - /// ///Adds an element with the provided key and value to the object. /// @@ -343,10 +329,6 @@ namespace Spring.Collections } } - #endregion - - #region IEnumerable implementation - /// ///Returns an enumerator that iterates through a collection. /// @@ -361,10 +343,6 @@ namespace Spring.Collections } } - #endregion - - #region Indexer - /// ///Gets or sets the element with the specified key. /// @@ -391,7 +369,5 @@ namespace Spring.Collections } } } - - #endregion } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Context/Attributes/ConfigurationClassPostProcessor.cs b/src/Spring/Spring.Core/Context/Attributes/ConfigurationClassPostProcessor.cs index 735891d2..f907fa14 100644 --- a/src/Spring/Spring.Core/Context/Attributes/ConfigurationClassPostProcessor.cs +++ b/src/Spring/Spring.Core/Context/Attributes/ConfigurationClassPostProcessor.cs @@ -37,12 +37,8 @@ namespace Spring.Context.Attributes /// public class ConfigurationClassPostProcessor : IObjectDefinitionRegistryPostProcessor, IOrdered { - #region Logging - private static readonly ILog Logger = LogManager.GetLogger(); - #endregion - private bool _postProcessObjectDefinitionRegistryCalled; private bool _postProcessObjectFactoryCalled; @@ -66,10 +62,7 @@ namespace Spring.Context.Attributes ///

/// /// The order value. - public int Order - { - get { return int.MinValue; } - } + public int Order => int.MinValue; /// /// Sets the problem reporter. diff --git a/src/Spring/Spring.Core/Context/Extension/GenericApplicationContextExtensions.cs b/src/Spring/Spring.Core/Context/Extension/GenericApplicationContextExtensions.cs index 0e3caee7..d7d1fefe 100644 --- a/src/Spring/Spring.Core/Context/Extension/GenericApplicationContextExtensions.cs +++ b/src/Spring/Spring.Core/Context/Extension/GenericApplicationContextExtensions.cs @@ -69,8 +69,9 @@ namespace Spring.Context.Support /// The assemblies to scan. public static void Scan(this GenericApplicationContext context, string assemblyScanPath, Func assemblyPredicate, Func typePredicate, params string[] assembliesToScan) { - AssemblyObjectDefinitionScanner scanner = - ArrayUtils.HasElements(assembliesToScan) ? new AssemblyObjectDefinitionScanner(assembliesToScan) : new AssemblyObjectDefinitionScanner(); + AssemblyObjectDefinitionScanner scanner = ArrayUtils.HasElements(assembliesToScan) + ? new AssemblyObjectDefinitionScanner(assembliesToScan) + : new AssemblyObjectDefinitionScanner(); scanner.ScanStartFolderPath = assemblyScanPath; diff --git a/src/Spring/Spring.Core/Context/Support/AbstractApplicationContext.cs b/src/Spring/Spring.Core/Context/Support/AbstractApplicationContext.cs index dd61ebcf..50acba73 100644 --- a/src/Spring/Spring.Core/Context/Support/AbstractApplicationContext.cs +++ b/src/Spring/Spring.Core/Context/Support/AbstractApplicationContext.cs @@ -1,5 +1,3 @@ -#region License - /* * Copyright © 2002-2011 the original author or authors. * @@ -16,10 +14,6 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Collections; using System.Collections.Generic; @@ -38,8 +32,6 @@ using Spring.Objects.Factory.Support; using Spring.Objects.Support; using Spring.Util; -#endregion - namespace Spring.Context.Support { /// @@ -79,8 +71,6 @@ namespace Spring.Context.Support public abstract class AbstractApplicationContext : ConfigurableResourceLoader, IConfigurableApplicationContext, IObjectDefinitionRegistry { - #region Constants - /// /// Name of the .Net config section that contains Spring.Net context definition. /// @@ -91,10 +81,6 @@ namespace Spring.Context.Support /// public const string DefaultRootContextName = "spring.root"; - #endregion - - #region Fields - private const long TicksAtEpoch = 621355968000000000; /// @@ -141,8 +127,8 @@ namespace Spring.Context.Support private IEventRegistry _eventRegistry; private IApplicationContext _parentApplicationContext; - private readonly IList _objectFactoryPostProcessors; - private readonly IList _defaultObjectPostProcessors; + private readonly List _objectFactoryPostProcessors; + private readonly List _defaultObjectPostProcessors; private string _name; private DateTime _startupDate; private readonly bool _isCaseSensitive; @@ -151,9 +137,6 @@ namespace Spring.Context.Support private bool _isInStart; private bool _isInStop; - #endregion - - /// /// Protects access to the internal object factory used by the ApplicationContext if attempted to be accessed when in improper state. /// @@ -163,13 +146,16 @@ namespace Spring.Context.Support { if (_isInStart || _isInStop || _isInDispose) { - throw new InvalidOperationException("Cannot Access ApplicationContext in this state!"); + ThrowInvalidApplicationContextState(); } return ObjectFactory; } - #region Constructor (s) / Destructor + private static void ThrowInvalidApplicationContextState() + { + throw new InvalidOperationException("Cannot Access ApplicationContext in this state!"); + } /// /// Creates a new instance of the @@ -218,7 +204,7 @@ namespace Spring.Context.Support protected AbstractApplicationContext(string name, bool caseSensitive, IApplicationContext parentApplicationContext) { - log = LogManager.GetLogger(this.GetType()); + log = LogManager.GetLogger(GetType()); _name = (StringUtils.IsNullOrEmpty(name)) ? DefaultRootContextName : name; _isCaseSensitive = caseSensitive; @@ -256,8 +242,6 @@ namespace Spring.Context.Support GC.SuppressFinalize(this); - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format( @@ -266,8 +250,6 @@ namespace Spring.Context.Support Name)); } - #endregion - // Closed event is raised before destroying objectfactory to enable registered IApplicationEventListeners // to handle the event before they get disposed. PublishEvent(this, new ContextClosedEventArgs()); @@ -277,10 +259,6 @@ namespace Spring.Context.Support _isInDispose = false; } - #endregion - - #region Abstract Methods - /// /// Subclasses must implement this method to perform the actual /// configuration loading. @@ -297,15 +275,10 @@ namespace Spring.Context.Support /// protected abstract void RefreshObjectFactory(); - #endregion - /// /// An object that can be used to synchronize access to the /// - public object SyncRoot - { - get { return this; } - } + public object SyncRoot => this; /// /// Set the to be used by this context. @@ -325,20 +298,13 @@ namespace Spring.Context.Support /// /// The timestamp (milliseconds) when this context was first loaded. /// - public long StartupDateMilliseconds - { - get { return (StartupDate.Ticks - TicksAtEpoch) / 10000; } - } - + public long StartupDateMilliseconds => (StartupDate.Ticks - TicksAtEpoch) / 10000; /// /// Gets a flag indicating whether context should be case sensitive. /// /// true if object lookups are case sensitive; otherwise, false. - public bool IsCaseSensitive - { - get { return _isCaseSensitive; } - } + public bool IsCaseSensitive => _isCaseSensitive; /// /// The for this context. @@ -390,17 +356,12 @@ namespace Spring.Context.Support /// protected IObjectFactory GetInternalParentObjectFactory() { - IConfigurableApplicationContext configContext - = _parentApplicationContext as IConfigurableApplicationContext; - if (configContext != null) + if (_parentApplicationContext is IConfigurableApplicationContext configContext) { - return ((IConfigurableApplicationContext) - _parentApplicationContext).ObjectFactory; - } - else - { - return _parentApplicationContext; + return configContext.ObjectFactory; } + + return _parentApplicationContext; } /// @@ -513,38 +474,43 @@ namespace Spring.Context.Support private void InvokeObjectFactoryPostProcessors(IConfigurableListableObjectFactory objectFactory) { // Invoke BeanDefinitionRegistryPostProcessors first, if any. - HashSet processedObjects = new HashSet(); + var processedObjects = new HashSet(); - if (objectFactory is IObjectDefinitionRegistry) + if (objectFactory is IObjectDefinitionRegistry registry) { - IObjectDefinitionRegistry registry = (IObjectDefinitionRegistry)objectFactory; - List regularPostProcessors = new List(); - List registryPostProcessors = new List(); + List regularPostProcessors = null; + List registryPostProcessors = null; - foreach (IObjectFactoryPostProcessor factoryProcessor in ObjectFactoryPostProcessors) + for (var i = 0; i < _objectFactoryPostProcessors.Count; i++) { - IObjectDefinitionRegistryPostProcessor registryPostProcessor = factoryProcessor as IObjectDefinitionRegistryPostProcessor; - if (registryPostProcessor != null) + IObjectFactoryPostProcessor factoryProcessor = _objectFactoryPostProcessors[i]; + if (factoryProcessor is IObjectDefinitionRegistryPostProcessor registryPostProcessor) { registryPostProcessor.PostProcessObjectDefinitionRegistry(registry); + registryPostProcessors = registryPostProcessors ?? new List(); registryPostProcessors.Add(registryPostProcessor); } else { + regularPostProcessors = regularPostProcessors ?? new List(); regularPostProcessors.Add(factoryProcessor); } } IDictionary objectMap = objectFactory.GetObjects(true, false); - List registryPostProcessorObjects = new List(objectMap.Values); - registryPostProcessorObjects.Sort(new OrderComparator()); - - foreach (object processor in registryPostProcessorObjects) + List registryPostProcessorObjects = null; + if (objectMap.Count > 0) { - ((IObjectDefinitionRegistryPostProcessor)processor).PostProcessObjectDefinitionRegistry(registry); + registryPostProcessorObjects = new List(objectMap.Values); + registryPostProcessorObjects.Sort(new OrderComparator()); + foreach (var processor in registryPostProcessorObjects) + { + processor.PostProcessObjectDefinitionRegistry(registry); + } } + InvokeObjectFactoryPostProcessors(registryPostProcessors, objectFactory); InvokeObjectFactoryPostProcessors(registryPostProcessorObjects, objectFactory); InvokeObjectFactoryPostProcessors(regularPostProcessors, objectFactory); @@ -559,8 +525,9 @@ namespace Spring.Context.Support } else { - foreach (IObjectFactoryPostProcessor factoryProcessor in ObjectFactoryPostProcessors) + for (var i = 0; i < _objectFactoryPostProcessors.Count; i++) { + IObjectFactoryPostProcessor factoryProcessor = _objectFactoryPostProcessors[i]; // Invoke factory processors registered with the context instance. factoryProcessor.PostProcessObjectFactory(objectFactory); } @@ -568,15 +535,13 @@ namespace Spring.Context.Support // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! - List factoryProcessorNames = new List(); - IList names = GetObjectNamesForType(typeof(IObjectFactoryPostProcessor), true, false); - factoryProcessorNames.AddRange(names); + IList factoryProcessorNames = GetObjectNamesForType(typeof(IObjectFactoryPostProcessor), true, false); // Separate between ObjectFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. - List priorityOrderedFactoryProcessors = new List(); - List orderedFactoryProcessorsNames = new List(); - List nonOrderedFactoryProcessorNames = new List(); + var priorityOrderedFactoryProcessors = new List(); + var orderedFactoryProcessorsNames = new List(); + var nonOrderedFactoryProcessorNames = new List(); for (int i = 0; i < factoryProcessorNames.Count; ++i) { @@ -603,7 +568,7 @@ namespace Spring.Context.Support InvokePriorityOrderedObjectFactoryPostProcessors(factoryProcessorNames, priorityOrderedFactoryProcessors); // Second, invoke those IObjectFactoryPostProcessors that implement IOrdered... - List orderedFactoryProcessors = new List(); + var orderedFactoryProcessors = new List(); foreach (string orderedFactoryProcessorsName in orderedFactoryProcessorsNames) { orderedFactoryProcessors.Add(SafeGetObjectFactory().GetObject(orderedFactoryProcessorsName)); @@ -612,28 +577,26 @@ namespace Spring.Context.Support InvokeObjectFactoryPostProcessors(orderedFactoryProcessors, SafeGetObjectFactory()); // and then the unordered ones... - List nonOrderedPostProcessors = new List(); - foreach (string nonOrderedFactoryProcessorName in nonOrderedFactoryProcessorNames) + if (nonOrderedFactoryProcessorNames.Count > 0) { - nonOrderedPostProcessors.Add(SafeGetObjectFactory().GetObject(nonOrderedFactoryProcessorName)); + var nonOrderedPostProcessors = new List(); + for (var i = 0; i < nonOrderedFactoryProcessorNames.Count; i++) + { + string nonOrderedFactoryProcessorName = nonOrderedFactoryProcessorNames[i]; + nonOrderedPostProcessors.Add(SafeGetObjectFactory().GetObject(nonOrderedFactoryProcessorName)); + } + InvokeObjectFactoryPostProcessors(nonOrderedPostProcessors, SafeGetObjectFactory()); } - InvokeObjectFactoryPostProcessors(nonOrderedPostProcessors, SafeGetObjectFactory()); - - #region Instrumentation if (log.IsDebugEnabled) { - log.Debug(string.Format( - CultureInfo.InvariantCulture, - "processed {0} IFactoryObjectPostProcessors defined in application context [{1}].", - factoryProcessorNames.Count, - Name)); + log.Debug($"processed {factoryProcessorNames.Count} IFactoryObjectPostProcessors defined in application context [{Name}]."); } - - #endregion } - protected virtual void InvokePriorityOrderedObjectFactoryPostProcessors(List factoryProcessorNames, List priorityOrderedFactoryProcessors) + protected virtual void InvokePriorityOrderedObjectFactoryPostProcessors( + IList factoryProcessorNames, + List priorityOrderedFactoryProcessors) { priorityOrderedFactoryProcessors.Sort(new OrderComparator()); InvokeObjectFactoryPostProcessors(priorityOrderedFactoryProcessors, SafeGetObjectFactory()); @@ -657,11 +620,17 @@ namespace Spring.Context.Support InvokeObjectFactoryPostProcessors(priorityOrderedFactoryProcessors, SafeGetObjectFactory()); } - private void InvokeObjectFactoryPostProcessors(IList objectFactoryPostProcessors, IConfigurableListableObjectFactory objectFactory) + private void InvokeObjectFactoryPostProcessors( + List objectFactoryPostProcessors, + IConfigurableListableObjectFactory objectFactory) where T : IObjectFactoryPostProcessor { - foreach (IObjectFactoryPostProcessor processor in objectFactoryPostProcessors) + if (objectFactoryPostProcessors == null) { - processor.PostProcessObjectFactory(objectFactory); + return; + } + for (var i = 0; i < objectFactoryPostProcessors.Count; i++) + { + objectFactoryPostProcessors[i].PostProcessObjectFactory(objectFactory); } } @@ -712,19 +681,13 @@ namespace Spring.Context.Support { _eventRegistry = (IEventRegistry)candidateRegistry; - #region Instrumentation - log.Debug(StringUtils.Surround( "Using IEventRegistry [", EventRegistry, "]")); - - #endregion } else { _eventRegistry = new EventRegistry(); - #region Instrumentation - if (log.IsWarnEnabled) { log.Warn(string.Format( @@ -733,24 +696,18 @@ namespace Spring.Context.Support "Falling back to default '{1}'.", EventRegistryObjectName, EventRegistry)); } - - #endregion } } else { _eventRegistry = new EventRegistry(); - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format( "No IEventRegistry found with name '{0}' : using default '{1}'.", EventRegistryObjectName, EventRegistry)); } - - #endregion } ICollection interestedParties = GetObjects(true, false).Values; foreach (IEventRegistryAware party in interestedParties) @@ -809,23 +766,17 @@ namespace Spring.Context.Support } } - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(StringUtils.Surround( "Using MessageSource [", MessageSource, "]")); } - - #endregion } else { _messageSource = new DelegatingMessageSource( GetInternalParentMessageSource()); - #region Instrumentation - if (log.IsWarnEnabled) { log.Warn(string.Format( @@ -834,8 +785,6 @@ namespace Spring.Context.Support "Falling back to default '{1}'.", MessageSourceObjectName, MessageSource)); } - - #endregion } } else if (ParentContext != null) @@ -844,32 +793,24 @@ namespace Spring.Context.Support GetInternalParentMessageSource()); SafeGetObjectFactory().RegisterSingleton(MessageSourceObjectName, _messageSource); - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format( "No message source found in the current context: using parent context's message source '{0}'.", MessageSource)); } - - #endregion } else { _messageSource = new StaticMessageSource(); SafeGetObjectFactory().RegisterSingleton(MessageSourceObjectName, _messageSource); - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format( "No IMessageSource found with name '{0}' : using default '{1}'.", MessageSourceObjectName, MessageSource)); } - - #endregion } } @@ -882,30 +823,6 @@ namespace Spring.Context.Support } } - /// - /// Returns the list of the - /// s - /// that will be applied to the objects created with this factory. - /// - /// - ///

- /// The elements of this list are instances of implementations of the - /// - /// interface. - ///

- ///
- /// - /// The list of the - /// s - /// that will be applied to the objects created with this factory. - /// - private IList ObjectFactoryPostProcessors - { - get { return _objectFactoryPostProcessors; } - } - - #region IConfigurableApplicationContext Members - /// /// Return the internal object factory of this application context. /// @@ -943,54 +860,34 @@ namespace Spring.Context.Support OnPreRefresh(); - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format("ApplicationContext Refresh: Refreshing object factory ")); } - #endregion - RefreshObjectFactory(); IConfigurableListableObjectFactory objectFactory = ObjectFactory; - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format("ApplicationContext Refresh: Registering well-known processors and objects")); } - #endregion - PrepareObjectFactory(objectFactory); - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format("ApplicationContext Refresh: Custom post processing object factory")); } - #endregion - PostProcessObjectFactory(objectFactory); - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format("ApplicationContext Refresh: Post processing object factory using pre-registered processors")); } - #endregion - - - - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format( @@ -1000,17 +897,11 @@ namespace Spring.Context.Support Name)); } - #endregion - - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format("ApplicationContext Refresh: Post processing object factory using defined processors")); } - #endregion - InvokeObjectFactoryPostProcessors(objectFactory); RegisterObjectPostProcessors(objectFactory); @@ -1021,27 +912,19 @@ namespace Spring.Context.Support OnRefresh(); - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format("ApplicationContext Refresh: Preinstantiating singletons")); } - #endregion - objectFactory.PreInstantiateSingletons(); OnPostRefresh(); - #region Instrumentation - if (log.IsInfoEnabled) { log.Info(string.Format("ApplicationContext Refresh: Completed")); } - - #endregion } } @@ -1072,7 +955,7 @@ namespace Spring.Context.Support // index 0 contains the ObjectPostProcessorChecker that is handled separately! for (int i = 1; i < _defaultObjectPostProcessors.Count; i++) { - objectFactory.AddObjectPostProcessor(this._defaultObjectPostProcessors[i]); + objectFactory.AddObjectPostProcessor(_defaultObjectPostProcessors[i]); } } @@ -1087,14 +970,10 @@ namespace Spring.Context.Support /// public virtual IApplicationContext ParentContext { - get { return _parentApplicationContext; } - set { _parentApplicationContext = value; } + get => _parentApplicationContext; + set => _parentApplicationContext = value; } - #endregion - - #region ILifecycle Members - /// /// Starts this component. /// @@ -1206,10 +1085,6 @@ namespace Spring.Context.Support } } - #endregion - - #region IApplicationContext Members - /// /// Raised in response to an implementation-dependant application /// context event. @@ -1223,10 +1098,7 @@ namespace Spring.Context.Support /// The representing when this context /// was first loaded. /// - public DateTime StartupDate - { - get { return _startupDate; } - } + public DateTime StartupDate => _startupDate; /// /// A name for this context. @@ -1236,16 +1108,10 @@ namespace Spring.Context.Support /// public string Name { - get { return _name; } - set { _name = value; } + get => _name; + set => _name = value; } - - - #endregion - - #region IListableObjectFactory Members - /// /// Return the names of objects matching the given /// (including subclasses), judging from the object definitions. @@ -1603,10 +1469,7 @@ namespace Spring.Context.Support /// The number of objects defined in the factory. /// /// - public int ObjectDefinitionCount - { - get { return SafeGetObjectFactory().ObjectDefinitionCount; } - } + public int ObjectDefinitionCount => SafeGetObjectFactory().ObjectDefinitionCount; /// /// Check if this object factory contains an object definition with the given name. @@ -1621,10 +1484,6 @@ namespace Spring.Context.Support return SafeGetObjectFactory().ContainsObjectDefinition(name); } - #endregion - - #region IObjectFactory Members - /// /// Return an instance (possibly shared or independent) of the given object name. /// @@ -1637,13 +1496,7 @@ namespace Spring.Context.Support /// If the object could not be created. /// /// - public object this[string name] - { - get - { - return SafeGetObjectFactory().GetObject(name); - } - } + public object this[string name] => SafeGetObjectFactory().GetObject(name); /// /// Does this object factory contain an object with the given name? @@ -2076,10 +1929,6 @@ namespace Spring.Context.Support return SafeGetObjectFactory().ConfigureObject(target, name, definition); } - #endregion - - #region IHierarchicalObjectFactory Members - /// /// Return the parent object factory, or if there is none. /// @@ -2087,10 +1936,7 @@ namespace Spring.Context.Support /// The parent object factory, or if there is none. /// /// - public IObjectFactory ParentObjectFactory - { - get { return _parentApplicationContext; } - } + public IObjectFactory ParentObjectFactory => _parentApplicationContext; /// /// Determines whether the local object factory contains a bean of the given name, @@ -2110,10 +1956,6 @@ namespace Spring.Context.Support return SafeGetObjectFactory().ContainsLocalObject(name); } - #endregion - - #region IObjectDefinitionRegistry Members - /// /// Determine whether the given object name is already in use within this context, /// i.e. whether there is a local object. May be override by subclasses, the default @@ -2164,10 +2006,6 @@ namespace Spring.Context.Support SafeGetObjectFactory().RegisterAlias(name, theAlias); } - #endregion - - #region IMessageSource Members - /// /// Resolve the message identified by the supplied /// . @@ -2420,10 +2258,6 @@ namespace Spring.Context.Support MessageSource.ApplyResources(value, objectName, culture); } - #endregion - - #region IEventRegistry Members - /// /// Publishes all events of the source object. /// @@ -2487,10 +2321,6 @@ namespace Spring.Context.Support _eventRegistry.Unsubscribe(subscriber, targetSourceType); } - #endregion - - #region IApplicationEventPublisher - /// /// Publishes an application context event. /// @@ -2508,8 +2338,6 @@ namespace Spring.Context.Support /// public void PublishEvent(object sender, ApplicationEventArgs e) { - #region Instrumentation - if (log.IsDebugEnabled) { log.Debug(string.Format( @@ -2518,8 +2346,6 @@ namespace Spring.Context.Support Name, e)); } - #endregion - OnContextEvent(sender, e); if (ParentContext != null) @@ -2528,10 +2354,6 @@ namespace Spring.Context.Support } } - #endregion - - #region IPostProcessor implementation - private sealed class ObjectPostProcessorChecker : IObjectPostProcessor, IOrdered { private static readonly ILog log = LogManager.GetLogger(); @@ -2553,26 +2375,17 @@ namespace Spring.Context.Support { if (_objectFactory.ObjectPostProcessorCount < _objectPostProcessorTargetCount) { - #region Instrumentation - if (log.IsInfoEnabled) { log.Info(string.Format( "Object '{0}' is not eligible for being processed by all " + "IObjectPostProcessors (for example: not eligible for auto-proxying).", objectName)); } - - #endregion } return obj; } - public int Order - { - get { return Int32.MinValue; } - } + public int Order => Int32.MinValue; } - - #endregion } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Context/Support/ApplicationContextAwareProcessor.cs b/src/Spring/Spring.Core/Context/Support/ApplicationContextAwareProcessor.cs index fa9a766e..2e7b5cd0 100644 --- a/src/Spring/Spring.Core/Context/Support/ApplicationContextAwareProcessor.cs +++ b/src/Spring/Spring.Core/Context/Support/ApplicationContextAwareProcessor.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,13 +18,9 @@ #endregion -#region Imports - using System.Runtime.Remoting; using Spring.Objects.Factory.Config; -#endregion - namespace Spring.Context.Support { /// @@ -64,7 +60,7 @@ namespace Spring.Context.Support /// Griffin Caprio (.NET) public class ApplicationContextAwareProcessor : IObjectPostProcessor { - private IApplicationContext _applicationContext; + private readonly IApplicationContext _applicationContext; /// /// Creates a new instance of the @@ -125,20 +121,17 @@ namespace Spring.Context.Support { if(!RemotingServices.IsTransparentProxy(obj)) { - if (typeof (IResourceLoaderAware).IsInstanceOfType(obj)) + if (obj is IResourceLoaderAware resourceLoaderAware) { - ((IResourceLoaderAware) obj).ResourceLoader - = _applicationContext; + resourceLoaderAware.ResourceLoader = _applicationContext; } - if (typeof (IMessageSourceAware).IsInstanceOfType(obj)) + if (obj is IMessageSourceAware messageSourceAware) { - ((IMessageSourceAware) obj).MessageSource - = _applicationContext; + messageSourceAware.MessageSource = _applicationContext; } - if (typeof (IApplicationContextAware).IsInstanceOfType(obj)) + if (obj is IApplicationContextAware applicationContextAware) { - ((IApplicationContextAware) obj).ApplicationContext - = _applicationContext; + applicationContextAware.ApplicationContext = _applicationContext; } } return obj; diff --git a/src/Spring/Spring.Core/Context/Support/ContextRegistry.cs b/src/Spring/Spring.Core/Context/Support/ContextRegistry.cs index 73e1600f..c211c29c 100644 --- a/src/Spring/Spring.Core/Context/Support/ContextRegistry.cs +++ b/src/Spring/Spring.Core/Context/Support/ContextRegistry.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -217,7 +217,7 @@ namespace Spring.Context.Support /// /// Has no effect if the context wasn't registered /// - /// ´the context to remove from the registry + /// The context to remove from the registry private static void UnregisterContext(IApplicationContext context) { AssertUtils.ArgumentNotNull(context, "context"); @@ -327,8 +327,6 @@ namespace Spring.Context.Support ctx.Dispose(); } - #region Instrumentation - // contexts will be removed from contextMap during OnContextEvent handler // but someone might choose to override AbstractApplicationContext.Dispose() without // calling base.Dispose() ... @@ -342,17 +340,13 @@ namespace Spring.Context.Support } } - #endregion - instance.contextMap.Clear(); + ConfigurationUtils.ClearCache(); rootContextName = null; // mark section dirty - force re-read from disk next time ConfigurationUtils.RefreshSection(AbstractApplicationContext.ContextSectionName); DynamicCodeManager.Clear(); - if (Cleared != null) - { - Cleared(typeof(ContextRegistry), EventArgs.Empty); - } + Cleared?.Invoke(typeof(ContextRegistry), EventArgs.Empty); } } @@ -375,22 +369,30 @@ namespace Spring.Context.Support private static void InitializeContextIfNeeded() { - if (rootContextName == null) + if (rootContextName != null) { - if (rootContextCurrentlyInCreation) - { - throw new InvalidOperationException("root context is currently in creation. You must not call ContextRegistry.GetContext() from e.g. constructors of your singleton objects"); - } + return; + } - rootContextCurrentlyInCreation = true; - try - { - ConfigurationUtils.GetSection(AbstractApplicationContext.ContextSectionName); - } - finally - { - rootContextCurrentlyInCreation = false; - } + DoInitializeRootContext(); + } + + private static void DoInitializeRootContext() + { + if (rootContextCurrentlyInCreation) + { + throw new InvalidOperationException( + "root context is currently in creation. You must not call ContextRegistry.GetContext() from e.g. constructors of your singleton objects"); + } + + rootContextCurrentlyInCreation = true; + try + { + ConfigurationUtils.GetSection(AbstractApplicationContext.ContextSectionName); + } + finally + { + rootContextCurrentlyInCreation = false; } } } diff --git a/src/Spring/Spring.Core/Core/IPriorityOrdered.cs b/src/Spring/Spring.Core/Core/IPriorityOrdered.cs index 6781bb3b..851ee04d 100644 --- a/src/Spring/Spring.Core/Core/IPriorityOrdered.cs +++ b/src/Spring/Spring.Core/Core/IPriorityOrdered.cs @@ -45,7 +45,5 @@ namespace Spring.Core /// public interface IPriorityOrdered : IOrdered { - } - } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/Factory/Attributes/AutowiredAttributeObjectPostProcessor.cs b/src/Spring/Spring.Core/Objects/Factory/Attributes/AutowiredAttributeObjectPostProcessor.cs index 24723547..75f3a805 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Attributes/AutowiredAttributeObjectPostProcessor.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Attributes/AutowiredAttributeObjectPostProcessor.cs @@ -389,7 +389,7 @@ namespace Spring.Objects.Factory.Attributes return; } - IList dependsOn = new List(objectDefinition.DependsOn); + var dependsOn = new List(objectDefinition.DependsOn); foreach (var name in autowiredObjectNames) { var autowiredObjectName = name as string; @@ -452,7 +452,7 @@ namespace Spring.Objects.Factory.Attributes else { var descriptor = new DependencyDescriptor(property, _required); - IList autowiredObjectNames = new ArrayList(); + var autowiredObjectNames = new List(); value = objectFactory.ResolveDependency(descriptor, objectName, autowiredObjectNames); lock (this) { @@ -464,7 +464,7 @@ namespace Spring.Objects.Factory.Attributes RegisterDependentObjects(objectName, autowiredObjectNames); if (autowiredObjectNames.Count == 1) { - var autowiredBeanName = autowiredObjectNames[0] as string; + var autowiredBeanName = autowiredObjectNames[0]; if (objectFactory.ContainsObject(autowiredBeanName)) { if (objectFactory.IsTypeMatch(autowiredBeanName, property.GetType())) @@ -524,7 +524,7 @@ namespace Spring.Objects.Factory.Attributes else { var descriptor = new DependencyDescriptor(field, _required); - IList autowiredObjectNames = new ArrayList(); + var autowiredObjectNames = new List(); value = objectFactory.ResolveDependency(descriptor, objectName, autowiredObjectNames); lock (this) { @@ -598,13 +598,12 @@ namespace Spring.Objects.Factory.Attributes Type[] paramTypes = method.GetParameters().Select(p => p.ParameterType).ToArray(); arguments = new Object[paramTypes.Length]; var descriptors = new DependencyDescriptor[paramTypes.Length]; - IList autowiredBeanNames = new ArrayList(); + var autowiredBeanNames = new List(); for (int i = 0; i < arguments.Length; i++) { MethodParameter methodParam = new MethodParameter(method, i); descriptors[i] = new DependencyDescriptor(methodParam, _required); - arguments[i] = objectFactory.ResolveDependency(descriptors[i], objectName, - autowiredBeanNames); + arguments[i] = objectFactory.ResolveDependency(descriptors[i], objectName, autowiredBeanNames); if (arguments[i] == null && !_required) { arguments = null; diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/ConstructorArgumentValues.cs b/src/Spring/Spring.Core/Objects/Factory/Config/ConstructorArgumentValues.cs index b95acdb0..78e296d3 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/ConstructorArgumentValues.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/ConstructorArgumentValues.cs @@ -1,5 +1,5 @@ /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,6 +39,17 @@ namespace Spring.Objects.Factory.Config [Serializable] public class ConstructorArgumentValues { + private static readonly CultureInfo enUSCultureInfo = new CultureInfo("en-US", false); + + private static readonly IReadOnlyDictionary _emptyIndexedArgumentValues = new Dictionary(); + private Dictionary _indexedArgumentValues = null; + + private static readonly IReadOnlyList _emptyGenericArgumentValues = new List(); + private List _genericArgumentValues = null; + + private static readonly IReadOnlyDictionary _emptyNamedArgumentValues = new Dictionary(); + private Dictionary _namedArgumentValues = null; + /// /// Can be used as an argument filler for the /// @@ -69,11 +80,6 @@ namespace Spring.Objects.Factory.Config AddAll(other); } - private static readonly CultureInfo enUSCultureInfo = new CultureInfo("en-US", false); - private IDictionary _indexedArgumentValues = new Dictionary(); - private List _genericArgumentValues = new List(); - private IDictionary _namedArgumentValues = new Dictionary(); - /// /// Return the map of indexed argument values. /// @@ -83,10 +89,8 @@ namespace Spring.Objects.Factory.Config /// s /// as values. /// - public virtual IDictionary IndexedArgumentValues - { - get { return _indexedArgumentValues; } - } + public IReadOnlyDictionary IndexedArgumentValues + => _indexedArgumentValues ?? _emptyIndexedArgumentValues; /// /// Return the map of named argument values. @@ -97,10 +101,7 @@ namespace Spring.Objects.Factory.Config /// s /// as values. /// - public virtual IDictionary NamedArgumentValues - { - get { return _namedArgumentValues; } - } + public IReadOnlyDictionary NamedArgumentValues => _namedArgumentValues ?? _emptyNamedArgumentValues; /// /// Return the set of generic argument values. @@ -109,41 +110,24 @@ namespace Spring.Objects.Factory.Config /// A of /// s. /// - public virtual IList GenericArgumentValues - { - get { return _genericArgumentValues; } - - } + public IReadOnlyList GenericArgumentValues => _genericArgumentValues ?? _emptyGenericArgumentValues; /// /// Return the number of arguments held in this instance. /// - public virtual int ArgumentCount - { - get - { - return IndexedArgumentValues.Count - + GenericArgumentValues.Count - + NamedArgumentValues.Count; - } - - } + public int ArgumentCount => IndexedArgumentValues.Count + + GenericArgumentValues.Count + + NamedArgumentValues.Count; /// /// Returns true if this holder does not contain any argument values, /// neither indexed ones nor generic ones. /// - public virtual bool Empty - { - get - { - return IndexedArgumentValues.Count == 0 - && GenericArgumentValues.Count == 0 - && NamedArgumentValues.Count == 0; - } - } + public bool Empty => IndexedArgumentValues.Count == 0 + && GenericArgumentValues.Count == 0 + && NamedArgumentValues.Count == 0; - /// + /// /// Copy all given argument values into this object. /// /// @@ -154,52 +138,63 @@ namespace Spring.Objects.Factory.Config { if (other != null) { - foreach (ValueHolder o in other.GenericArgumentValues) + if (other._genericArgumentValues != null && other._genericArgumentValues.Count > 0) { - GenericArgumentValues.Add(o); + GetAndInitializeGenericArgumentValuesIfNeeded().AddRange(other._genericArgumentValues); } - foreach (KeyValuePair entry in other.IndexedArgumentValues) + + if (other._indexedArgumentValues != null && other._indexedArgumentValues.Count > 0) { - ValueHolder vh = entry.Value; - if (vh != null) - { - AddOrMergeIndexedArgumentValues( entry.Key, vh.Copy()); - } + foreach (var entry in other._indexedArgumentValues) + { + ValueHolder vh = entry.Value; + if (vh != null) + { + AddOrMergeIndexedArgumentValues(entry.Key, vh.Copy()); + } + } } - foreach (KeyValuePair entry in other.NamedArgumentValues) + + if (other._namedArgumentValues != null && other._namedArgumentValues.Count > 0) { - AddOrMergeNamedArgumentValues(entry.Key, entry.Value); - //NamedArgumentValues.Add(entry.Key, entry.Value); + foreach (var entry in other._namedArgumentValues) + { + AddOrMergeNamedArgumentValues(entry.Key, entry.Value); + //NamedArgumentValues.Add(entry.Key, entry.Value); + } } } } private void AddOrMergeNamedArgumentValues(string key, object newValue) { - if (_namedArgumentValues.ContainsKey(key) ) - { - _namedArgumentValues[key] = newValue; - } else - { - _namedArgumentValues.Add(key, newValue); - } + var namedArgumentValues = GetAndInitializeNamedArgumentValuesIfNeeded(); + if (namedArgumentValues.ContainsKey(key)) + { + namedArgumentValues[key] = newValue; + } + else + { + namedArgumentValues.Add(key, newValue); + } } private void AddOrMergeIndexedArgumentValues(int key, ValueHolder newValue) { - ValueHolder currentValue; - IMergable mergable = newValue.Value as IMergable; - if (_indexedArgumentValues.TryGetValue(key, out currentValue) && mergable != null ) + var dictionary = GetAndInitializeIndexedArgumentValuesIfNeeded(); + + if (newValue.Value is IMergable mergable + && dictionary.TryGetValue(key, out var currentValue)) { if (mergable.MergeEnabled) { newValue.Value = mergable.Merge(currentValue.Value); } } - _indexedArgumentValues[key] = newValue; + dictionary[key] = newValue; } - /// + /// /// Add argument value for the given index in the constructor argument list. /// /// @@ -208,9 +203,9 @@ namespace Spring.Objects.Factory.Config /// /// The argument value. /// - public virtual void AddIndexedArgumentValue(int index, object value) + public void AddIndexedArgumentValue(int index, object value) { - IndexedArgumentValues[index] = new ValueHolder(value); + GetAndInitializeIndexedArgumentValuesIfNeeded()[index] = new ValueHolder(value); } /// @@ -222,9 +217,9 @@ namespace Spring.Objects.Factory.Config /// The of the argument /// . /// - public virtual void AddIndexedArgumentValue(int index, object value, string type) + public void AddIndexedArgumentValue(int index, object value, string type) { - IndexedArgumentValues[index] = new ValueHolder(value, type); + GetAndInitializeIndexedArgumentValuesIfNeeded()[index] = new ValueHolder(value, type); } /// @@ -236,10 +231,10 @@ namespace Spring.Objects.Factory.Config /// If the supplied is /// or is composed wholly of whitespace. /// - public virtual void AddNamedArgumentValue(string name, object value) + public void AddNamedArgumentValue(string name, object value) { AssertUtils.ArgumentHasText(name, "name"); - NamedArgumentValues[GetCanonicalNamedArgument(name)] = new ValueHolder(value); + GetAndInitializeNamedArgumentValuesIfNeeded()[GetCanonicalNamedArgument(name)] = new ValueHolder(value); } /// @@ -254,7 +249,7 @@ namespace Spring.Objects.Factory.Config /// /// for the argument, or if none set. /// - public virtual ValueHolder GetIndexedArgumentValue(int index, Type requiredType) + public ValueHolder GetIndexedArgumentValue(int index, Type requiredType) { ValueHolder valueHolder; if (IndexedArgumentValues.TryGetValue(index, out valueHolder)) @@ -278,15 +273,16 @@ namespace Spring.Objects.Factory.Config /// /// for the argument, or if none set. /// - public virtual ValueHolder GetNamedArgumentValue(string name) - { - ValueHolder valueHolder = null; - if (name != null && ContainsNamedArgument(name)) - { - valueHolder = (ValueHolder)NamedArgumentValues[GetCanonicalNamedArgument(name)]; - } - return valueHolder; - } + public ValueHolder GetNamedArgumentValue(string name) + { + ValueHolder valueHolder = null; + if (name != null && ContainsNamedArgument(name)) + { + valueHolder = (ValueHolder) GetAndInitializeNamedArgumentValuesIfNeeded()[GetCanonicalNamedArgument(name)]; + } + + return valueHolder; + } /// /// Does this set of constructor arguments contain a named argument matching the @@ -305,7 +301,7 @@ namespace Spring.Objects.Factory.Config /// public bool ContainsNamedArgument(string argument) { - return NamedArgumentValues.ContainsKey(GetCanonicalNamedArgument(argument)); + return _namedArgumentValues != null && _namedArgumentValues.ContainsKey(GetCanonicalNamedArgument(argument)); } /// @@ -314,9 +310,9 @@ namespace Spring.Objects.Factory.Config /// /// The argument value. /// - public virtual void AddGenericArgumentValue(object value) + public void AddGenericArgumentValue(object value) { - GenericArgumentValues.Add(new ValueHolder(value)); + GetAndInitializeGenericArgumentValuesIfNeeded().Add(new ValueHolder(value)); } /// @@ -327,9 +323,9 @@ namespace Spring.Objects.Factory.Config /// The of the argument /// . /// - public virtual void AddGenericArgumentValue(object value, string type) + public void AddGenericArgumentValue(object value, string type) { - GenericArgumentValues.Add(new ValueHolder(value, type)); + GetAndInitializeGenericArgumentValuesIfNeeded().Add(new ValueHolder(value, type)); } /// @@ -344,7 +340,7 @@ namespace Spring.Objects.Factory.Config /// /// for the argument, or if none set. /// - public virtual ValueHolder GetGenericArgumentValue(Type requiredType) + public ValueHolder GetGenericArgumentValue(Type requiredType) { return GetGenericArgumentValue(requiredType, null); } @@ -369,11 +365,18 @@ namespace Spring.Objects.Factory.Config /// /// for the argument, or if none set. /// - public virtual ValueHolder GetGenericArgumentValue( - Type requiredType, ISet usedValues) + public ValueHolder GetGenericArgumentValue( + Type requiredType, + ISet usedValues) { - foreach (ValueHolder valueHolder in GenericArgumentValues) + if (_genericArgumentValues == null) { + return null; + } + + for (var i = 0; i < _genericArgumentValues.Count; i++) + { + ValueHolder valueHolder = _genericArgumentValues[i]; if (usedValues == null || !usedValues.Contains(valueHolder)) { if (requiredType != null) @@ -381,25 +384,26 @@ namespace Spring.Objects.Factory.Config if (StringUtils.HasText(valueHolder.Type)) { if (valueHolder.Type.Equals(requiredType.FullName) - || valueHolder.Type.Equals(requiredType.AssemblyQualifiedName)) + || valueHolder.Type.Equals(requiredType.AssemblyQualifiedName)) { return valueHolder; } } else if (requiredType.IsInstanceOfType(valueHolder.Value) - || (requiredType.IsArray - && typeof (IList).IsInstanceOfType(valueHolder.Value))) + || (requiredType.IsArray + && valueHolder.Value is IList)) { return valueHolder; } } - // if the value holder is (pretty much) untyped, that's ok to return... + // if the value holder is (pretty much) untyped, that's ok to return... else if (StringUtils.IsNullOrEmpty(valueHolder.Type)) { return valueHolder; } } } + return null; } @@ -419,7 +423,7 @@ namespace Spring.Objects.Factory.Config /// /// for the argument, or if none is set. /// - public virtual ValueHolder GetArgumentValue(int index, Type requiredType) + public ValueHolder GetArgumentValue(int index, Type requiredType) { return GetArgumentValue(index, string.Empty, requiredType, null); } @@ -448,7 +452,7 @@ namespace Spring.Objects.Factory.Config /// /// for the argument, or if none is set. /// - public virtual ValueHolder GetArgumentValue(int index, Type requiredType, ISet usedValues) + public ValueHolder GetArgumentValue(int index, Type requiredType, ISet usedValues) { return GetArgumentValue(index, string.Empty, requiredType, usedValues); } @@ -471,7 +475,7 @@ namespace Spring.Objects.Factory.Config /// /// for the argument, or if none is set. /// - public virtual ValueHolder GetArgumentValue(string name, Type requiredType) + public ValueHolder GetArgumentValue(string name, Type requiredType) { return GetArgumentValue(NoIndex, name, requiredType, null); } @@ -502,7 +506,7 @@ namespace Spring.Objects.Factory.Config /// /// for the argument, or if none is set. /// - public virtual ValueHolder GetArgumentValue( + public ValueHolder GetArgumentValue( string name, Type requiredType, ISet usedValues) { return GetArgumentValue(NoIndex, name, requiredType, usedValues); @@ -539,7 +543,7 @@ namespace Spring.Objects.Factory.Config /// /// for the argument, or if none is set. /// - public virtual ValueHolder GetArgumentValue( + public ValueHolder GetArgumentValue( int index, string name, Type requiredType, ISet usedValues) { ValueHolder valueHolder = null; @@ -562,6 +566,21 @@ namespace Spring.Objects.Factory.Config { return argument != null ? argument.ToLower(enUSCultureInfo) : argument; } + + private Dictionary GetAndInitializeIndexedArgumentValuesIfNeeded() + { + return _indexedArgumentValues = _indexedArgumentValues ?? new Dictionary(); + } + + private Dictionary GetAndInitializeNamedArgumentValuesIfNeeded() + { + return _namedArgumentValues = _namedArgumentValues ?? new Dictionary(); + } + + private List GetAndInitializeGenericArgumentValuesIfNeeded() + { + return _genericArgumentValues = _genericArgumentValues ?? new List(); + } /// /// Holder for a constructor argument value, with an optional @@ -571,7 +590,10 @@ namespace Spring.Objects.Factory.Config [Serializable] public class ValueHolder { - /// + private object _ctorValue; + private readonly string typeName; + + /// /// Creates a new instance of the ValueHolder class. /// /// @@ -631,21 +653,15 @@ namespace Spring.Objects.Factory.Config /// public object Value { - get { return _ctorValue; } - set { _ctorValue = value; } - } + get => _ctorValue; + set => _ctorValue = value; + } /// /// Return the of the constructor /// argument. /// - public string Type - { - get { return typeName; } - } - - private object _ctorValue; - private string typeName; + public string Type => typeName; } } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/EventValues.cs b/src/Spring/Spring.Core/Objects/Factory/Config/EventValues.cs index 7d7107b1..1e28a21e 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/EventValues.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/EventValues.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +14,10 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Collections; using System.Collections.Generic; -#endregion - namespace Spring.Objects.Factory.Config { /// @@ -33,21 +25,24 @@ namespace Spring.Objects.Factory.Config /// /// Rick Evans (.NET) [Serializable] - public class EventValues + public class EventValues { - #region Constants /// /// The empty array of s. /// - private static readonly IEventHandlerValue [] EmptyHandlers = new IEventHandlerValue [] {}; - #endregion + private static readonly IEventHandlerValue[] EmptyHandlers = { }; + + private static readonly string[] EmptyKeys = { }; + + private Dictionary> _eventHandlers; - #region Constructor (s) / Destructor /// /// Creates a new instance of the /// class. /// - public EventValues() {} + public EventValues() + { + } /// /// Creates a new instance of the @@ -59,56 +54,33 @@ namespace Spring.Objects.Factory.Config /// public EventValues(EventValues other) { - AddAll (other); - } - #endregion - - #region Properties - /// - /// The mapping of event names to an - /// of - /// s. - /// - protected IDictionary> EventHandlers - { - get - { - return _eventHandlers; - } + AddAll(other); } /// /// Gets the of events /// that have handlers associated with them. /// - public ICollection Events - { - get - { - return EventHandlers.Keys; - } - } + public ICollection Events => (ICollection) _eventHandlers?.Keys ?? EmptyKeys; /// /// Gets the of /// s for the supplied /// event name. /// - public ICollection this [string eventName] + public ICollection this[string eventName] { get { - IList handlers; - if (!EventHandlers.TryGetValue(eventName, out handlers)) + if (_eventHandlers == null || !_eventHandlers.TryGetValue(eventName, out var handlers)) { - handlers = EventValues.EmptyHandlers; + return EmptyHandlers; } + return handlers; } } - #endregion - #region Methods /// /// Copy all given argument values into this object. /// @@ -116,15 +88,16 @@ namespace Spring.Objects.Factory.Config /// The /// to be used to populate this instance. /// - public void AddAll (EventValues other) + public void AddAll(EventValues other) { - if (other != null) + if (other?._eventHandlers != null) { - foreach (IList handlers in other.EventHandlers.Values) + foreach (var pair in other._eventHandlers) { - foreach (IEventHandlerValue handler in handlers) + var list = pair.Value; + for (var i = 0; i < list.Count; i++) { - AddHandler (handler); + AddHandler(list[i]); } } } @@ -134,21 +107,17 @@ namespace Spring.Objects.Factory.Config /// Adds the supplied handler to the collection of event handlers. /// /// The handler to be added. - public void AddHandler (IEventHandlerValue handler) + public void AddHandler(IEventHandlerValue handler) { - IList handlers; + _eventHandlers = _eventHandlers ?? new Dictionary>(); - if (!EventHandlers.TryGetValue(handler.EventName, out handlers)) + if (!_eventHandlers.TryGetValue(handler.EventName, out var handlers)) { handlers = new List(); - EventHandlers [handler.EventName] = handlers; + _eventHandlers[handler.EventName] = handlers; } - handlers.Add (handler); - } - #endregion - #region Fields - private IDictionary> _eventHandlers = new Dictionary>(); - #endregion - } + handlers.Add(handler); + } + } } diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/IAutowireCapableObjectFactory.cs b/src/Spring/Spring.Core/Objects/Factory/Config/IAutowireCapableObjectFactory.cs index c7163d89..4de8aab6 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/IAutowireCapableObjectFactory.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/IAutowireCapableObjectFactory.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,126 +21,127 @@ #region Imports using System; -using System.Collections; +using System.Collections.Generic; #endregion namespace Spring.Objects.Factory.Config { - /// - /// Extension of the - /// interface to be implemented by object factories that are capable of - /// autowiring and expose this functionality for existing object instances. - /// - /// Juergen Hoeller - /// Rick Evans (.NET) + /// + /// Extension of the + /// interface to be implemented by object factories that are capable of + /// autowiring and expose this functionality for existing object instances. + /// + /// Juergen Hoeller + /// Rick Evans (.NET) public interface IAutowireCapableObjectFactory : IObjectFactory { - /// - /// Create a new object instance of the given class with the specified - /// autowire strategy. - /// - /// - /// The of the object to instantiate. - /// - /// - /// The desired autowiring mode. - /// - /// - /// Whether to perform a dependency check for objects (not applicable to - /// autowiring a constructor, thus ignored there). - /// - /// The new object instance. - /// - /// If the wiring fails. - /// - /// - object Autowire ( - Type type, AutoWiringMode autowireMode, bool dependencyCheck); - - /// - /// Autowire the object properties of the given object instance by name or - /// . - /// - /// - /// The existing object instance. - /// - /// - /// The desired autowiring mode. - /// - /// - /// Whether to perform a dependency check for the object. - /// - /// - /// If the wiring fails. - /// - /// - void AutowireObjectProperties ( - object instance, AutoWiringMode autowireMode, bool dependencyCheck); - - /// - /// Apply s - /// to the given existing object instance, invoking their - /// - /// methods. - /// - /// - ///

- /// The returned object instance may be a wrapper around the original. - ///

- ///
- /// - /// The existing object instance. - /// - /// - /// The name of the object. - /// - /// - /// The object instance to use, either the original or a wrapped one. - /// - /// - /// If any post-processing failed. - /// - /// - object ApplyObjectPostProcessorsBeforeInitialization ( - object instance, string name); - - /// - /// Apply s - /// to the given existing object instance, invoking their - /// - /// methods. - /// - /// - ///

- /// The returned object instance may be a wrapper around the original. - ///

- ///
- /// - /// The existing object instance. - /// - /// - /// The name of the object. - /// - /// - /// The object instance to use, either the original or a wrapped one. - /// - /// - /// If any post-processing failed. - /// - /// - object ApplyObjectPostProcessorsAfterInitialization ( - object instance, string name); + /// + /// Create a new object instance of the given class with the specified + /// autowire strategy. + /// + /// + /// The of the object to instantiate. + /// + /// + /// The desired autowiring mode. + /// + /// + /// Whether to perform a dependency check for objects (not applicable to + /// autowiring a constructor, thus ignored there). + /// + /// The new object instance. + /// + /// If the wiring fails. + /// + /// + object Autowire(Type type, AutoWiringMode autowireMode, bool dependencyCheck); - /// - /// Resolve the specified dependency against the objects defined in this factory. - /// - /// The descriptor for the dependency. - /// Name of the object which declares the present dependency. - /// A list that all names of autowired object (used for - /// resolving the present dependency) are supposed to be added to. - /// the resolved object, or null if none found - /// if dependency resolution failed - object ResolveDependency(DependencyDescriptor descriptor, string objectName, IList autowiredObjectNames); + /// + /// Autowire the object properties of the given object instance by name or + /// . + /// + /// + /// The existing object instance. + /// + /// + /// The desired autowiring mode. + /// + /// + /// Whether to perform a dependency check for the object. + /// + /// + /// If the wiring fails. + /// + /// + void AutowireObjectProperties(object instance, AutoWiringMode autowireMode, bool dependencyCheck); + + /// + /// Apply s + /// to the given existing object instance, invoking their + /// + /// methods. + /// + /// + ///

+ /// The returned object instance may be a wrapper around the original. + ///

+ ///
+ /// + /// The existing object instance. + /// + /// + /// The name of the object. + /// + /// + /// The object instance to use, either the original or a wrapped one. + /// + /// + /// If any post-processing failed. + /// + /// + object ApplyObjectPostProcessorsBeforeInitialization(object instance, string name); + + /// + /// Apply s + /// to the given existing object instance, invoking their + /// + /// methods. + /// + /// + ///

+ /// The returned object instance may be a wrapper around the original. + ///

+ ///
+ /// + /// The existing object instance. + /// + /// + /// The name of the object. + /// + /// + /// The object instance to use, either the original or a wrapped one. + /// + /// + /// If any post-processing failed. + /// + /// + object ApplyObjectPostProcessorsAfterInitialization(object instance, string name); + + /// + /// Resolve the specified dependency against the objects defined in this factory. + /// + /// The descriptor for the dependency. + /// Name of the object which declares the present dependency. + /// + /// A list that all names of autowired object (used for + /// resolving the present dependency) are supposed to be added to. + /// + /// the resolved object, or null if none found + /// if dependency resolution failed + object ResolveDependency( + DependencyDescriptor descriptor, + string objectName, + IList autowiredObjectNames); } -} +} \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/IObjectDefinition.cs b/src/Spring/Spring.Core/Objects/Factory/Config/IObjectDefinition.cs index fbc180ca..1cd9b561 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/IObjectDefinition.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/IObjectDefinition.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -179,7 +179,7 @@ namespace Spring.Objects.Factory.Config /// preparation on startup. ///

/// - IList DependsOn { get; } + IReadOnlyList DependsOn { get; } /// /// The name of the initializer method. diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/IObjectPostProcessor.cs b/src/Spring/Spring.Core/Objects/Factory/Config/IObjectPostProcessor.cs index c0a651d7..bfbec461 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/IObjectPostProcessor.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/IObjectPostProcessor.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/InstantiationAwareObjectPostProcessorAdapter.cs b/src/Spring/Spring.Core/Objects/Factory/Config/InstantiationAwareObjectPostProcessorAdapter.cs index 2d357fad..aafb088a 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/InstantiationAwareObjectPostProcessorAdapter.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/InstantiationAwareObjectPostProcessorAdapter.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +14,6 @@ * limitations under the License. */ -#endregion - using System; using System.Collections.Generic; using System.Reflection; @@ -41,8 +37,6 @@ namespace Spring.Objects.Factory.Config /// Mark Pollack (.NET) public abstract class InstantiationAwareObjectPostProcessorAdapter : SmartInstantiationAwareObjectPostProcessor { - #region SmartInstantiationAwareObjectPostProcessor Members - /// /// Predicts the type of the object to be eventually returned from this /// processors PostProcessBeforeInstantiation callback. @@ -68,10 +62,6 @@ namespace Spring.Objects.Factory.Config return null; } - #endregion - - #region IInstantiationAwareObjectPostProcessor Members - /// /// Apply this /// @@ -159,10 +149,6 @@ namespace Spring.Objects.Factory.Config return pvs; } - #endregion - - #region IObjectPostProcessor Members - /// /// Apply this /// to the given new object instance before any object initialization callbacks. @@ -216,7 +202,5 @@ namespace Spring.Objects.Factory.Config { return instance; } - - #endregion } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/ObjectDefinitionVisitor.cs b/src/Spring/Spring.Core/Objects/Factory/Config/ObjectDefinitionVisitor.cs index 31f23ce4..386e22b1 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/ObjectDefinitionVisitor.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/ObjectDefinitionVisitor.cs @@ -21,8 +21,8 @@ #region Imports using System; -using System.Collections; -using System.Collections.Generic; +using System.Collections; +using System.Collections.Generic; using System.Collections.Specialized; using Spring.Collections; @@ -51,7 +51,7 @@ namespace Spring.Objects.Factory.Config /// /// Initializes a new instance of the class. /// - /// The handler to be called for resolving variables contained in a string. + /// The handler to be called for resolving variables contained in a string. public ObjectDefinitionVisitor(ResolveHandler resolveHandler) { AssertUtils.ArgumentNotNull(resolveHandler, "ResovleHandler"); @@ -125,44 +125,44 @@ namespace Spring.Objects.Factory.Config } } } - } - - /// - /// Visits the indexed constructor argument values, replacing string values using the - /// specified IVariableSource. - /// - /// The indexed argument values. - protected virtual void VisitIndexedArgumentValues(IDictionary ias) + } + + /// + /// Visits the indexed constructor argument values, replacing string values using the + /// specified IVariableSource. + /// + /// The indexed argument values. + protected virtual void VisitIndexedArgumentValues(IReadOnlyDictionary ias) { foreach (ConstructorArgumentValues.ValueHolder valueHolder in ias.Values) { ConfigureConstructorArgument(valueHolder); } - } - - /// - /// Visits the named constructor argument values, replacing string values using the - /// specified IVariableSource. - /// - /// The named argument values. - protected virtual void VisitNamedArgumentValues(IDictionary nav) + } + + /// + /// Visits the named constructor argument values, replacing string values using the + /// specified IVariableSource. + /// + /// The named argument values. + protected virtual void VisitNamedArgumentValues(IReadOnlyDictionary nav) { foreach (ConstructorArgumentValues.ValueHolder valueHolder in nav.Values) { ConfigureConstructorArgument(valueHolder); } - } - - /// - /// Visits the generic constructor argument values, replacing string values using - /// the specified IVariableSource. - /// - /// The genreic argument values. - protected virtual void VisitGenericArgumentValues(ICollection gav) + } + + /// + /// Visits the generic constructor argument values, replacing string values using + /// the specified IVariableSource. + /// + /// The genreic argument values. + protected virtual void VisitGenericArgumentValues(IReadOnlyList gav) { - foreach (ConstructorArgumentValues.ValueHolder valueHolder in gav) + for (var i = 0; i < gav.Count; i++) { - ConfigureConstructorArgument(valueHolder); + ConfigureConstructorArgument(gav[i]); } } @@ -186,17 +186,16 @@ namespace Spring.Objects.Factory.Config /// the resolved value protected virtual object ResolveValue(object value) { - if (value is IObjectDefinition) + if (value is IObjectDefinition definition) { - VisitObjectDefinition((IObjectDefinition)value); + VisitObjectDefinition(definition); } - else if (value is ObjectDefinitionHolder) + else if (value is ObjectDefinitionHolder definitionHolder) { - VisitObjectDefinition( ((ObjectDefinitionHolder)value).ObjectDefinition); + VisitObjectDefinition( definitionHolder.ObjectDefinition); } - else if (value is RuntimeObjectReference) + else if (value is RuntimeObjectReference ror) { - RuntimeObjectReference ror = (RuntimeObjectReference)value; //name has to be of string type. string newObjectName = ResolveStringValue(ror.ObjectName); if (!newObjectName.Equals(ror.ObjectName)) @@ -204,25 +203,24 @@ namespace Spring.Objects.Factory.Config return new RuntimeObjectReference(newObjectName); } } - else if (value is ManagedList) + else if (value is ManagedList list) { - VisitManagedList((ManagedList)value); + VisitManagedList(list); } - else if (value is ManagedSet) + else if (value is ManagedSet set) { - VisitManagedSet((ManagedSet)value); + VisitManagedSet(set); } - else if (value is ManagedDictionary) + else if (value is ManagedDictionary dictionary) { - VisitManagedDictionary((ManagedDictionary)value); + VisitManagedDictionary(dictionary); } - else if (value is NameValueCollection) + else if (value is NameValueCollection collection) { - VisitNameValueCollection((NameValueCollection)value); + VisitNameValueCollection(collection); } - else if (value is TypedStringValue) + else if (value is TypedStringValue typedStringValue) { - TypedStringValue typedStringValue = (TypedStringValue)value; String stringValue = typedStringValue.Value; if (stringValue != null) { @@ -230,13 +228,12 @@ namespace Spring.Objects.Factory.Config typedStringValue.Value = visitedString; } } - else if (value is string) + else if (value is string s) { - return ResolveStringValue((string)value); + return ResolveStringValue(s); } - else if (value is ExpressionHolder) + else if (value is ExpressionHolder holder) { - ExpressionHolder holder = (ExpressionHolder)value; string newExpressionString = ResolveStringValue(holder.ExpressionString); return new ExpressionHolder(newExpressionString); } @@ -335,27 +332,27 @@ namespace Spring.Objects.Factory.Config if (!ObjectUtils.NullSafeEquals(newValue, oldValue)) { mods[entry.Key] = newValue; - }*/ - - object key = entry.Key; - object newKey = ResolveValue(key); - object oldValue = entry.Value; - object newValue = ResolveValue(oldValue); - - if (!ObjectUtils.NullSafeEquals(newValue, oldValue) || key != newKey) - { - entriesModified = true; + }*/ + + object key = entry.Key; + object newKey = ResolveValue(key); + object oldValue = entry.Value; + object newValue = ResolveValue(oldValue); + + if (!ObjectUtils.NullSafeEquals(newValue, oldValue) || key != newKey) + { + entriesModified = true; } mods[newKey] = newValue; - } - if (entriesModified) - { - dictVal.Clear(); - foreach (DictionaryEntry entry in mods) - { - dictVal[entry.Key] = entry.Value; - } + } + if (entriesModified) + { + dictVal.Clear(); + foreach (DictionaryEntry entry in mods) + { + dictVal[entry.Key] = entry.Value; + } } } @@ -379,9 +376,9 @@ namespace Spring.Objects.Factory.Config /// /// calls the to resolve any variables contained in the raw string. - /// + /// /// the raw string value containing variable placeholders to be resolved - /// If no has been configured. + /// If no has been configured. /// the resolved string, having variables being replaced, if any protected virtual string ResolveStringValue(string rawStringValue) { @@ -389,8 +386,8 @@ namespace Spring.Objects.Factory.Config { throw new InvalidOperationException("No resolveHandler specified - pass an instance " + "into the constructor or override the 'ResolveStringValue' method"); - } - + } + return resolveHandler(rawStringValue); } } diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/SmartInstantiationAwareObjectPostProcessor.cs b/src/Spring/Spring.Core/Objects/Factory/Config/SmartInstantiationAwareObjectPostProcessor.cs index 5bf161bc..46dbb6e6 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/SmartInstantiationAwareObjectPostProcessor.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/SmartInstantiationAwareObjectPostProcessor.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Objects/Factory/IListableObjectFactory.cs b/src/Spring/Spring.Core/Objects/Factory/IListableObjectFactory.cs index 67c5fbed..305629eb 100644 --- a/src/Spring/Spring.Core/Objects/Factory/IListableObjectFactory.cs +++ b/src/Spring/Spring.Core/Objects/Factory/IListableObjectFactory.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Objects/Factory/IObjectFactory.cs b/src/Spring/Spring.Core/Objects/Factory/IObjectFactory.cs index 7ffba218..c7fdf4b6 100644 --- a/src/Spring/Spring.Core/Objects/Factory/IObjectFactory.cs +++ b/src/Spring/Spring.Core/Objects/Factory/IObjectFactory.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Objects/Factory/ObjectFactoryUtils.cs b/src/Spring/Spring.Core/Objects/Factory/ObjectFactoryUtils.cs index 41b8fe7c..55299166 100644 --- a/src/Spring/Spring.Core/Objects/Factory/ObjectFactoryUtils.cs +++ b/src/Spring/Spring.Core/Objects/Factory/ObjectFactoryUtils.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ using System; using System.Collections.Generic; - +using System.Runtime.CompilerServices; using Spring.Util; #endregion @@ -44,8 +44,6 @@ namespace Spring.Objects.Factory /// Rick Evans (.NET) public sealed class ObjectFactoryUtils { - #region Constructor (s) / Destructor - // CLOVER:OFF /// @@ -64,8 +62,6 @@ namespace Spring.Objects.Factory // CLOVER:ON - #endregion - /// /// Used to dereference an /// and distinguish it from managed objects created by the factory. @@ -90,7 +86,7 @@ namespace Spring.Objects.Factory /// time that the name becomes unique. ///

/// - public const string GENERATED_OBJECT_NAME_SEPARATOR = "#"; + public const string GeneratedObjectNameSeparator = "#"; /// /// Count all object definitions in any hierarchy in which this @@ -375,12 +371,12 @@ namespace Spring.Objects.Factory public static string TransformedObjectName(string name) { AssertUtils.ArgumentNotNull(name, "name", "Object name must not be null."); - if (!ObjectFactoryUtils.IsFactoryDereference(name)) + if (!IsFactoryDereference(name)) { return name; } - string objectName = name.Substring(ObjectFactoryUtils.FactoryObjectPrefix.Length); + string objectName = name.Substring(FactoryObjectPrefix.Length); return objectName; } @@ -399,7 +395,7 @@ namespace Spring.Objects.Factory /// public static string BuildFactoryObjectName(string objectName) { - return ObjectFactoryUtils.FactoryObjectPrefix + objectName; + return FactoryObjectPrefix + objectName; } /// @@ -422,24 +418,17 @@ namespace Spring.Objects.Factory /// value. /// /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsFactoryDereference(string name) { - return name != null - && name.Length > ObjectFactoryUtils.FactoryObjectPrefix.Length - && name[0] == ObjectFactoryUtils.FactoryObjectPrefix[0] - && name.StartsWith(ObjectFactoryUtils.FactoryObjectPrefix) - ; + return name != null && name.Length > 1 && name[0] == '&'; } - #region Private Utility Methods - private static IListableObjectFactory GetParentListableObjectFactoryIfAny(IListableObjectFactory factory) { - IHierarchicalObjectFactory hierFactory = factory as IHierarchicalObjectFactory; - if (hierFactory != null) + if (factory is IHierarchicalObjectFactory hierFactory) { - return - hierFactory.ParentObjectFactory as IListableObjectFactory; + return hierFactory.ParentObjectFactory as IListableObjectFactory; } return null; } @@ -450,12 +439,8 @@ namespace Spring.Objects.Factory { return ObjectUtils.EnumerateFirstElement(objectsOfType.Values); } - else - { - throw new NoSuchObjectDefinitionException(type, "Expected single object but found " + objectsOfType.Count); - } - } - #endregion + throw new NoSuchObjectDefinitionException(type, "Expected single object but found " + objectsOfType.Count); + } } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/AbstractAutowireCapableObjectFactory.cs b/src/Spring/Spring.Core/Objects/Factory/Support/AbstractAutowireCapableObjectFactory.cs index ea73be50..82f03b74 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/AbstractAutowireCapableObjectFactory.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/AbstractAutowireCapableObjectFactory.cs @@ -1,5 +1,5 @@ /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ using System; using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Reflection; @@ -92,8 +93,8 @@ namespace Spring.Objects.Factory.Support protected AbstractAutowireCapableObjectFactory(bool caseSensitive, IObjectFactory parentFactory) : base(caseSensitive, parentFactory) { - this.IgnoreDependencyInterface(typeof(IObjectFactoryAware)); - this.IgnoreDependencyInterface(typeof(IObjectNameAware)); + IgnoreDependencyInterface(typeof(IObjectFactoryAware)); + IgnoreDependencyInterface(typeof(IObjectNameAware)); } /// @@ -102,8 +103,8 @@ namespace Spring.Objects.Factory.Support /// protected IInstantiationStrategy InstantiationStrategy { - get { return instantiationStrategy; } - set { instantiationStrategy = value; } + get => instantiationStrategy; + set => instantiationStrategy = value; } /// @@ -276,21 +277,21 @@ namespace Spring.Objects.Factory.Support { if (log.IsDebugEnabled) { - log.Debug(string.Format("Invoking IInstantiationAwareObjectPostProcessors before " + "the instantiation of '{0}'.", objectName)); + log.Debug("Invoking IInstantiationAwareObjectPostProcessors before " + + $"the instantiation of '{objectName}'."); } - foreach (IObjectPostProcessor processor in ObjectPostProcessors) + for (var i = 0; i < ObjectPostProcessors.Count; i++) { + IObjectPostProcessor processor = ObjectPostProcessors[i]; IInstantiationAwareObjectPostProcessor inProc = processor as IInstantiationAwareObjectPostProcessor; - if (inProc != null) + object theObject = inProc?.PostProcessBeforeInstantiation(objectType, objectName); + if (theObject != null) { - object theObject = inProc.PostProcessBeforeInstantiation(objectType, objectName); - if (theObject != null) - { - return theObject; - } + return theObject; } } + return null; } @@ -311,19 +312,19 @@ namespace Spring.Objects.Factory.Support { log.Debug(m => m("Invoking PostProcessBeforeDestruction after IDisposal of object '" + name + "'")); - foreach (IObjectPostProcessor objectProcessor in ObjectPostProcessors) + for (var i = 0; i < ObjectPostProcessors.Count; i++) { - if (objectProcessor is IDestructionAwareObjectPostProcessor) + IObjectPostProcessor objectProcessor = ObjectPostProcessors[i]; + if (objectProcessor is IDestructionAwareObjectPostProcessor processor) { try { - ((IDestructionAwareObjectPostProcessor)objectProcessor).PostProcessBeforeDestruction(instance, name); + processor.PostProcessBeforeDestruction(instance, name); } catch (Exception ex) { log.ErrorFormat( - string.Format("Error during execution of {0}.PostProcessBeforeDestruction for object {1}", - objectProcessor.GetType().Name, name), ex); + $"Error during execution of {processor.GetType().Name}.PostProcessBeforeDestruction for object {name}", ex); } } } @@ -360,7 +361,7 @@ namespace Spring.Objects.Factory.Support ObjectDefinitionValueResolver valueResolver = CreateValueResolver(); MutablePropertyValues deepCopy = new MutablePropertyValues(properties); - IList copiedProperties = deepCopy.PropertyValues; + var copiedProperties = deepCopy.PropertyValues; for (int i = 0; i < copiedProperties.Count; ++i) { PropertyValue copiedProperty = copiedProperties[i]; @@ -482,10 +483,10 @@ namespace Spring.Objects.Factory.Support if (HasInstantiationAwareBeanPostProcessors) { - foreach (IObjectPostProcessor processor in ObjectPostProcessors) + for (var i = 0; i < ObjectPostProcessors.Count; i++) { - IInstantiationAwareObjectPostProcessor inProc = processor as IInstantiationAwareObjectPostProcessor; - if (inProc != null) + IObjectPostProcessor processor = ObjectPostProcessors[i]; + if (processor is IInstantiationAwareObjectPostProcessor inProc) { if (!inProc.PostProcessAfterInstantiation(wrapper.WrappedInstance, name)) { @@ -535,21 +536,19 @@ namespace Spring.Objects.Factory.Support bool hasInstAwareOpps = HasInstantiationAwareBeanPostProcessors; bool needsDepCheck = (definition.DependencyCheck != DependencyCheckingMode.None); - if (hasInstAwareOpps || needsDepCheck) { - IList filteredPropInfo = FilterPropertyInfoForDependencyCheck(wrapper); + List filteredPropInfo = null; if (hasInstAwareOpps) { - foreach (IObjectPostProcessor processor in ObjectPostProcessors) + for (var i = 0; i < ObjectPostProcessors.Count; i++) { - IInstantiationAwareObjectPostProcessor instantiationAwareObjectPostProcessor = - processor as IInstantiationAwareObjectPostProcessor; - if (instantiationAwareObjectPostProcessor != null) + IObjectPostProcessor processor = ObjectPostProcessors[i]; + if (processor is IInstantiationAwareObjectPostProcessor instantiationAwareObjectPostProcessor) { - properties = - instantiationAwareObjectPostProcessor.PostProcessPropertyValues(properties, filteredPropInfo, wrapper.WrappedInstance, - name); + filteredPropInfo = filteredPropInfo ?? FilterPropertyInfoForDependencyCheck(wrapper); + properties = instantiationAwareObjectPostProcessor.PostProcessPropertyValues(properties, + filteredPropInfo, wrapper.WrappedInstance, name); if (properties == null) { return; @@ -560,6 +559,7 @@ namespace Spring.Objects.Factory.Support if (needsDepCheck) { + filteredPropInfo = filteredPropInfo ?? FilterPropertyInfoForDependencyCheck(wrapper); CheckDependencies(name, definition, filteredPropInfo, properties); } @@ -939,7 +939,7 @@ namespace Spring.Objects.Factory.Support /// protected virtual void RemoveEagerlyCachedSingleton(string objectName, IObjectDefinition objectDefinition) { - base.RemoveSingleton(objectName); + RemoveSingleton(objectName); } /// @@ -1022,12 +1022,14 @@ namespace Spring.Objects.Factory.Support { if (HasInstantiationAwareBeanPostProcessors) { - foreach (IObjectPostProcessor objectPostProcessor in ObjectPostProcessors) + for (var i = 0; i < ObjectPostProcessors.Count; i++) { - if (ObjectUtils.IsAssignable(typeof(SmartInstantiationAwareObjectPostProcessor), objectPostProcessor)) + IObjectPostProcessor objectPostProcessor = ObjectPostProcessors[i]; + if (ObjectUtils.IsAssignable(typeof(SmartInstantiationAwareObjectPostProcessor), + objectPostProcessor)) { SmartInstantiationAwareObjectPostProcessor iop = - (SmartInstantiationAwareObjectPostProcessor)objectPostProcessor; + (SmartInstantiationAwareObjectPostProcessor) objectPostProcessor; ConstructorInfo[] ctors = iop.DetermineCandidateConstructors(objectType, objectName); if (ctors != null) { @@ -1142,13 +1144,12 @@ namespace Spring.Objects.Factory.Support IList filteredPropInfo = FilterPropertyInfoForDependencyCheck(wrapper); if (HasInstantiationAwareBeanPostProcessors) { - foreach (IObjectPostProcessor processor in ObjectPostProcessors) + for (var i = 0; i < ObjectPostProcessors.Count; i++) { - IInstantiationAwareObjectPostProcessor inProc = processor as IInstantiationAwareObjectPostProcessor; - if (inProc != null) + IObjectPostProcessor processor = ObjectPostProcessors[i]; + if (processor is IInstantiationAwareObjectPostProcessor inProc) { - properties = - inProc.PostProcessPropertyValues(properties, filteredPropInfo, wrapper.WrappedInstance, name); + properties = inProc.PostProcessPropertyValues(properties, filteredPropInfo, wrapper.WrappedInstance, name); if (properties == null) { return; @@ -1179,30 +1180,22 @@ namespace Spring.Objects.Factory.Support /// /// The object wrapper the object was created with. /// The filtered PropertyInfos - private IList FilterPropertyInfoForDependencyCheck(IObjectWrapper wrapper) + private List FilterPropertyInfoForDependencyCheck(IObjectWrapper wrapper) { - lock (filteredPropertyDescriptorsCache) + return filteredPropertyDescriptorsCache.GetOrAdd(wrapper.WrappedType, t => { - IList filtered; - if (!filteredPropertyDescriptorsCache.TryGetValue(wrapper.WrappedType, out filtered)) + var list = new List(wrapper.GetPropertyInfos()); + for (int i = list.Count - 1; i >= 0; i--) { - - List list = new List(wrapper.GetPropertyInfos()); - for (int i = list.Count - 1; i >= 0; i--) + PropertyInfo pi = list[i]; + if (IsExcludedFromDependencyCheck(pi)) { - PropertyInfo pi = list[i]; - if (IsExcludedFromDependencyCheck(pi)) - { - list.RemoveAt(i); - } + list.RemoveAt(i); } - - filtered = list; - filteredPropertyDescriptorsCache.Add(wrapper.WrappedType, filtered); } - return filtered; - } + return list; + }); } /// @@ -1898,17 +1891,18 @@ namespace Spring.Objects.Factory.Support } object result = instance; - foreach (IObjectPostProcessor objectProcessor in ObjectPostProcessors) + for (var i = 0; i < ObjectPostProcessors.Count; i++) { + IObjectPostProcessor objectProcessor = ObjectPostProcessors[i]; result = objectProcessor.PostProcessBeforeInitialization(result, name); if (result == null) { throw new ObjectCreationException(name, - string.Format(CultureInfo.InvariantCulture, - "PostProcessBeforeInitialization method of IObjectPostProcessor [{0}] " - + " returned null for object [{1}] with name '{2}'.", objectProcessor, instance, name)); + $"PostProcessBeforeInitialization method of IObjectPostProcessor [{objectProcessor}] " + + $" returned null for object [{instance}] with name '{name}'."); } } + return result; } @@ -1939,17 +1933,19 @@ namespace Spring.Objects.Factory.Support } object result = instance; - foreach (IObjectPostProcessor objectProcessor in ObjectPostProcessors) + for (var i = 0; i < ObjectPostProcessors.Count; i++) { + IObjectPostProcessor objectProcessor = ObjectPostProcessors[i]; result = objectProcessor.PostProcessAfterInitialization(result, name); if (result == null) { throw new ObjectCreationException(name, - string.Format(CultureInfo.InvariantCulture, - "PostProcessAfterInitialization method of IObjectPostProcessor [{0}] " - + " returned null for object [{1}] with name [{2}].", objectProcessor, instance, name)); + string.Format(CultureInfo.InvariantCulture, + "PostProcessAfterInitialization method of IObjectPostProcessor [{0}] " + + " returned null for object [{1}] with name [{2}].", objectProcessor, instance, name)); } } + return result; } @@ -1959,55 +1955,44 @@ namespace Spring.Objects.Factory.Support /// The descriptor for the dependency. /// Name of the object which declares the present dependency. /// A list that all names of autowired object (used for - /// resolving the present dependency) are supposed to be added to. + /// resolving the present dependency) are supposed to be added to. /// /// the resolved object, or null if none found /// /// if dependency resolution failed - public abstract object ResolveDependency(DependencyDescriptor descriptor, string objectName, - IList autowiredObjectNames); + public abstract object ResolveDependency( + DependencyDescriptor descriptor, + string objectName, + IList autowiredObjectNames); private IInstantiationStrategy instantiationStrategy = new MethodInjectingInstantiationStrategy(); /// /// Cache of filtered PropertyInfos: object Type -> PropertyInfo array /// - private IDictionary> filteredPropertyDescriptorsCache = new Dictionary>(); + private readonly ConcurrentDictionary> filteredPropertyDescriptorsCache = new ConcurrentDictionary>(); /// /// Dependency interfaces to ignore on dependency check and autowire, as Set of /// Class objects. By default, only the IObjectFactoryAware and IObjectNameAware /// interfaces are ignored. /// - private ISet ignoredDependencyInterfaces = new HybridSet(); + private readonly HybridSet ignoredDependencyInterfaces = new HybridSet(); } internal class UnsatisfiedDependencyExceptionData { - private int parameterIndex; - private Type parameterType; - private string errorMessage; - public UnsatisfiedDependencyExceptionData(int parameterIndex, Type parameterType, string errorMessage) { - this.parameterIndex = parameterIndex; - this.parameterType = parameterType; - this.errorMessage = errorMessage; + ParameterIndex = parameterIndex; + ParameterType = parameterType; + ErrorMessage = errorMessage; } - public int ParameterIndex - { - get { return parameterIndex; } - } + public int ParameterIndex { get; } - public Type ParameterType - { - get { return parameterType; } - } + public Type ParameterType { get; } - public string ErrorMessage - { - get { return errorMessage; } - } + public string ErrorMessage { get; } } } diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/AbstractObjectDefinition.cs b/src/Spring/Spring.Core/Objects/Factory/Support/AbstractObjectDefinition.cs index 354f7156..81a884c9 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/AbstractObjectDefinition.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/AbstractObjectDefinition.cs @@ -1,5 +1,5 @@ /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,34 @@ namespace Spring.Objects.Factory.Support [Serializable] public abstract class AbstractObjectDefinition : ObjectMetadataAttributeAccessor, IConfigurableObjectDefinition, ISerializable { - private static readonly string SCOPE_SINGLETON = "singleton"; - private static readonly string SCOPE_PROTOTYPE = "prototype"; + private const string ScopeSingleton = "singleton"; + private const string ScopePrototype = "prototype"; + + private ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues(); + private MutablePropertyValues propertyValues = new MutablePropertyValues(); + private EventValues eventHandlerValues = new EventValues(); + private MethodOverrides methodOverrides = new MethodOverrides(); + private string resourceDescription; + private bool isSingleton = true; + private bool isPrototype; + private bool isLazyInit; + private bool isAbstract; + private string scope = ScopeSingleton; + private ObjectRole role = ObjectRole.ROLE_APPLICATION; + + private string objectTypeName; + private Type objectType; + + private AutoWiringMode autowireMode = AutoWiringMode.No; + private DependencyCheckingMode dependencyCheck = DependencyCheckingMode.None; + private List dependsOn; + private bool autowireCandidate = true; + private bool primary; + private Dictionary qualifiers; + private string initMethodName; + private string destroyMethodName; + private string factoryMethodName; + private string factoryObjectName; /// /// Creates a new instance of the @@ -71,12 +97,8 @@ namespace Spring.Objects.Factory.Support /// protected AbstractObjectDefinition(ConstructorArgumentValues arguments, MutablePropertyValues properties) { - constructorArgumentValues = - (arguments != null) ? arguments : new ConstructorArgumentValues(); - propertyValues = - (properties != null) ? properties : new MutablePropertyValues(); - eventHandlerValues = new EventValues(); - DependsOn = StringUtils.EmptyStrings; + constructorArgumentValues = arguments ?? constructorArgumentValues ?? new ConstructorArgumentValues(); + propertyValues = properties ?? propertyValues ?? new MutablePropertyValues(); } /// @@ -97,7 +119,7 @@ namespace Spring.Objects.Factory.Support protected AbstractObjectDefinition(IObjectDefinition other) { AssertUtils.ArgumentNotNull(other, "other"); - this.OverrideFrom(other); + OverrideFrom(other); AbstractObjectDefinition aod = other as AbstractObjectDefinition; if (aod != null) @@ -129,7 +151,10 @@ namespace Spring.Objects.Factory.Support IsAutowireCandidate = other.IsAutowireCandidate; IsPrimary = other.IsPrimary; CopyQualifiersFrom(aod); - DependsOn = new List(other.DependsOn); + if (other.DependsOn.Count > 0) + { + DependsOn = other.DependsOn; + } FactoryMethodName = other.FactoryMethodName; FactoryObjectName = other.FactoryObjectName; AutowireMode = other.AutowireMode; @@ -160,8 +185,8 @@ namespace Spring.Objects.Factory.Support /// public MutablePropertyValues PropertyValues { - get { return propertyValues; } - set { propertyValues = value == null ? new MutablePropertyValues() : value; } + get => propertyValues; + set => propertyValues = value ?? new MutablePropertyValues(); } /// @@ -172,10 +197,7 @@ namespace Spring.Objects.Factory.Support /// if this definition has at least one /// . /// - public bool HasMethodOverrides - { - get { return !MethodOverrides.IsEmpty; } - } + public bool HasMethodOverrides => !MethodOverrides.IsEmpty; /// /// The constructor argument values for this object. @@ -195,8 +217,8 @@ namespace Spring.Objects.Factory.Support /// public ConstructorArgumentValues ConstructorArgumentValues { - get { return constructorArgumentValues; } - set { constructorArgumentValues = value == null ? new ConstructorArgumentValues() : value; } + get => constructorArgumentValues; + set => constructorArgumentValues = value ?? new ConstructorArgumentValues(); } /// @@ -217,8 +239,8 @@ namespace Spring.Objects.Factory.Support /// public EventValues EventHandlerValues { - get { return eventHandlerValues; } - set { eventHandlerValues = value == null ? new EventValues() : value; } + get => eventHandlerValues; + set => eventHandlerValues = value ?? new EventValues(); } /// @@ -239,8 +261,8 @@ namespace Spring.Objects.Factory.Support /// public MethodOverrides MethodOverrides { - get { return methodOverrides; } - set { methodOverrides = value == null ? new MethodOverrides() : value; } + get => methodOverrides; + set => methodOverrides = value ?? new MethodOverrides(); } /// @@ -250,13 +272,13 @@ namespace Spring.Objects.Factory.Support /// public virtual string Scope { - get { return scope; } + get => scope; set { AssertUtils.ArgumentNotNull(value, "Scope"); - this.scope = value; - this.isPrototype = 0 == string.Compare(SCOPE_PROTOTYPE, value, true); - this.isSingleton = !isPrototype; // 0 == string.Compare(SCOPE_SINGLETON, value, true); + scope = value; + isPrototype = 0 == string.Compare(ScopePrototype, value, StringComparison.OrdinalIgnoreCase); + isSingleton = !isPrototype; // 0 == string.Compare(SCOPE_SINGLETON, value, true); } } @@ -265,8 +287,8 @@ namespace Spring.Objects.Factory.Support /// public virtual ObjectRole Role { - get { return role; } - set { role = value; } + get => role; + set => role = value; } /// @@ -288,10 +310,10 @@ namespace Spring.Objects.Factory.Support /// public virtual bool IsSingleton { - get { return isSingleton; } + get => isSingleton; set { - scope = (value ? SCOPE_SINGLETON : SCOPE_PROTOTYPE); + scope = (value ? ScopeSingleton : ScopePrototype); isSingleton = value; isPrototype = !value; } @@ -304,10 +326,7 @@ namespace Spring.Objects.Factory.Support /// /// true if this instance is prototype; otherwise, false. /// - public virtual bool IsPrototype - { - get { return isPrototype; } - } + public virtual bool IsPrototype => isPrototype; /// /// Is this object lazily initialized? @@ -323,8 +342,8 @@ namespace Spring.Objects.Factory.Support /// public bool IsLazyInit { - get { return isLazyInit; } - set { isLazyInit = value; } + get => isLazyInit; + set => isLazyInit = value; } /// @@ -335,16 +354,7 @@ namespace Spring.Objects.Factory.Support /// /// if this object definition is a "template". /// - public bool IsTemplate - { - get - { - return ( - isAbstract || - (objectType == null && StringUtils.IsNullOrEmpty(factoryObjectName)) - ); - } - } + public bool IsTemplate => isAbstract || (objectType == null && StringUtils.IsNullOrEmpty(factoryObjectName)); /// /// Is this object definition "abstract", i.e. not meant to be @@ -356,8 +366,8 @@ namespace Spring.Objects.Factory.Support /// public bool IsAbstract { - get { return isAbstract; } - set { isAbstract = value; } + get => isAbstract; + set => isAbstract = value; } /// @@ -375,24 +385,26 @@ namespace Spring.Objects.Factory.Support { get { - if (!HasObjectType) + if (objectType == null) { - throw new ApplicationException( - "Object definition does not carry a resolved System.Type"); + ThrowApplicationException("Object definition does not carry a resolved System.Type"); + return null; } - return (Type) objectType; + return objectType; } - set { objectType = value; } + set => objectType = value; + } + + private static void ThrowApplicationException(string message) + { + throw new ApplicationException(message); } /// /// Is the of the object definition a resolved /// ? /// - public bool HasObjectType - { - get { return objectType is Type; } - } + public bool HasObjectType => objectType != null; /// /// Returns the of the @@ -400,29 +412,18 @@ namespace Spring.Objects.Factory.Support /// public string ObjectTypeName { - get - { - if (objectType is Type) - { - return ((Type) objectType).FullName; - } - else - { - return objectType as string; - } - } - set { objectType = StringUtils.GetTextOrNull(value); } + get => objectTypeName ?? objectType?.FullName; + set => objectTypeName = StringUtils.GetTextOrNull(value); } - /// /// A description of the resource that this object definition /// came from (for the purpose of showing context in case of errors). /// public string ResourceDescription { - get { return resourceDescription; } - set { resourceDescription = StringUtils.GetTextOrNull(value); } + get => resourceDescription; + set => resourceDescription = StringUtils.GetTextOrNull(value); } /// @@ -438,8 +439,8 @@ namespace Spring.Objects.Factory.Support /// public AutoWiringMode AutowireMode { - get { return autowireMode; } - set { autowireMode = value; } + get => autowireMode; + set => autowireMode = value; } /// @@ -493,8 +494,8 @@ namespace Spring.Objects.Factory.Support /// public DependencyCheckingMode DependencyCheck { - get { return dependencyCheck; } - set { dependencyCheck = value; } + get => dependencyCheck; + set => dependencyCheck = value; } /// @@ -512,10 +513,10 @@ namespace Spring.Objects.Factory.Support /// preparation on startup. /// /// - public IList DependsOn + public IReadOnlyList DependsOn { - get { return dependsOn; } - set { dependsOn = value ?? StringUtils.EmptyStrings; } + get => dependsOn ?? StringUtils.EmptyStringsList; + set => dependsOn = value != null && value.Count > 0 ? new List(value) : null; } /// @@ -527,8 +528,8 @@ namespace Spring.Objects.Factory.Support /// public bool IsAutowireCandidate { - get { return autowireCandidate; } - set { autowireCandidate = value;} + get => autowireCandidate; + set => autowireCandidate = value; } @@ -539,8 +540,8 @@ namespace Spring.Objects.Factory.Support /// public bool IsPrimary { - get { return primary; } - set { primary = value; } + get => primary; + set => primary = value; } /// @@ -550,6 +551,7 @@ namespace Spring.Objects.Factory.Support /// public void AddQualifier(AutowireCandidateQualifier qualifier) { + qualifiers = qualifiers ?? new Dictionary(); qualifiers.Add(qualifier.TypeName, qualifier); } @@ -558,7 +560,7 @@ namespace Spring.Objects.Factory.Support /// public bool HasQualifier(string typeName) { - return qualifiers.ContainsKey(typeName); + return qualifiers != null && qualifiers.ContainsKey(typeName); } /// @@ -566,7 +568,12 @@ namespace Spring.Objects.Factory.Support /// public AutowireCandidateQualifier GetQualifier(string typeName) { - return qualifiers.ContainsKey(typeName) ? qualifiers[typeName] : null; + if (qualifiers != null && qualifiers.TryGetValue(typeName, out var qualifier)) + { + return qualifier; + } + + return null; } /// @@ -575,7 +582,9 @@ namespace Spring.Objects.Factory.Support /// the Set of objects. public Set GetQualifiers() { - return new OrderedSet(qualifiers.Values); + return qualifiers != null + ? new OrderedSet(qualifiers.Values) + : new OrderedSet(); } /// @@ -585,10 +594,16 @@ namespace Spring.Objects.Factory.Support public void CopyQualifiersFrom(AbstractObjectDefinition source) { Trace.Assert(source != null, "Source must not be null"); - foreach (var qualifier in source.qualifiers) + if (source.qualifiers != null && source.qualifiers.Count > 0) { - if (!qualifiers.Contains(qualifier)) - qualifiers.Add(qualifier); + qualifiers = qualifiers ?? new Dictionary(); + foreach (var qualifier in source.qualifiers) + { + if (!qualifiers.ContainsKey(qualifier.Key)) + { + qualifiers.Add(qualifier.Key, qualifier.Value); + } + } } } @@ -603,8 +618,8 @@ namespace Spring.Objects.Factory.Support /// public string InitMethodName { - get { return initMethodName; } - set { initMethodName = StringUtils.GetTextOrNull(value); } + get => initMethodName; + set => initMethodName = StringUtils.GetTextOrNull(value); } /// @@ -618,8 +633,8 @@ namespace Spring.Objects.Factory.Support /// public string DestroyMethodName { - get { return destroyMethodName; } - set { destroyMethodName = StringUtils.GetTextOrNull(value); } + get => destroyMethodName; + set => destroyMethodName = StringUtils.GetTextOrNull(value); } /// @@ -635,8 +650,8 @@ namespace Spring.Objects.Factory.Support /// public string FactoryMethodName { - get { return factoryMethodName; } - set { factoryMethodName = StringUtils.GetTextOrNull(value); } + get => factoryMethodName; + set => factoryMethodName = StringUtils.GetTextOrNull(value); } /// @@ -644,8 +659,8 @@ namespace Spring.Objects.Factory.Support /// public string FactoryObjectName { - get { return factoryObjectName; } - set { factoryObjectName = StringUtils.GetTextOrNull(value); } + get => factoryObjectName; + set => factoryObjectName = StringUtils.GetTextOrNull(value); } /// @@ -657,14 +672,8 @@ namespace Spring.Objects.Factory.Support /// /// property. /// - public virtual bool HasConstructorArgumentValues - { - get - { - return ConstructorArgumentValues != null - && !ConstructorArgumentValues.Empty; - } - } + public virtual bool HasConstructorArgumentValues => ConstructorArgumentValues != null + && !ConstructorArgumentValues.Empty; /// /// Resolves the type of the object, resolving it from a specified @@ -684,7 +693,7 @@ namespace Spring.Objects.Factory.Support return null; } Type resolvedType = TypeResolutionUtils.ResolveType(typeName); - this.ObjectType = resolvedType; + ObjectType = resolvedType; return resolvedType; } @@ -719,7 +728,7 @@ namespace Spring.Objects.Factory.Support public virtual void PrepareMethodOverrides() { // ascertain that the various lookup methods exist... - foreach (MethodOverride mo in MethodOverrides.Overrides) + foreach (MethodOverride mo in MethodOverrides) { PrepareMethodOverride(mo); } @@ -786,7 +795,8 @@ namespace Spring.Objects.Factory.Support } if (other.DependsOn != null && other.DependsOn.Count > 0) { - List deps = new List(other.DependsOn); + var deps = new List(other.DependsOn.Count + (DependsOn?.Count).GetValueOrDefault()); + deps.AddRange(other.DependsOn); if (DependsOn != null && DependsOn.Count > 0) { deps.AddRange(DependsOn); @@ -797,10 +807,13 @@ namespace Spring.Objects.Factory.Support ResourceDescription = other.ResourceDescription; IsPrimary = other.IsPrimary; IsAutowireCandidate = other.IsAutowireCandidate; - - AbstractObjectDefinition aod = other as AbstractObjectDefinition; - if (aod != null) + + if (other is AbstractObjectDefinition aod) { + if (other.ObjectTypeName != null) + { + ObjectTypeName = other.ObjectTypeName; + } if (aod.HasObjectType) { ObjectType = other.ObjectType; @@ -842,31 +855,7 @@ namespace Spring.Objects.Factory.Support } return buffer.ToString(); } - - private ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues(); - private MutablePropertyValues propertyValues = new MutablePropertyValues(); - private EventValues eventHandlerValues = new EventValues(); - private MethodOverrides methodOverrides = new MethodOverrides(); - private string resourceDescription = null; - private bool isSingleton = true; - private bool isPrototype = false; - private bool isLazyInit = false; - private bool isAbstract = false; - private string scope = SCOPE_SINGLETON; - private ObjectRole role = ObjectRole.ROLE_APPLICATION; - private object objectType; - private AutoWiringMode autowireMode = AutoWiringMode.No; - private DependencyCheckingMode dependencyCheck = DependencyCheckingMode.None; - private IList dependsOn; - private bool autowireCandidate = true; - private bool primary; - private readonly IDictionary qualifiers = new Dictionary(); - private string initMethodName = null; - private string destroyMethodName = null; - private string factoryMethodName = null; - private string factoryObjectName = null; - - + protected AbstractObjectDefinition(SerializationInfo info, StreamingContext context) { constructorArgumentValues = (ConstructorArgumentValues) info.GetValue("constructorArgumentValues", typeof(ConstructorArgumentValues)); @@ -886,10 +875,10 @@ namespace Spring.Objects.Factory.Support autowireMode = (AutoWiringMode) info.GetValue("autowireMode", typeof(AutoWiringMode)); dependencyCheck= (DependencyCheckingMode) info.GetValue("dependencyCheck", typeof(DependencyCheckingMode)); - dependsOn = (IList) info.GetValue("dependsOn", typeof(IList)); + dependsOn = (List) info.GetValue("dependsOn", typeof(List)); autowireCandidate = info.GetBoolean("autowireCandidate"); primary = info.GetBoolean("primary"); - qualifiers = (IDictionary) info.GetValue("qualifiers", typeof(IDictionary)); + qualifiers = (Dictionary) info.GetValue("qualifiers", typeof(Dictionary)); initMethodName = info.GetString("initMethodName"); destroyMethodName = info.GetString("destroyMethodName"); factoryMethodName = info.GetString("factoryMethodName" ); @@ -909,16 +898,7 @@ namespace Spring.Objects.Factory.Support info.AddValue("isAbstract", isAbstract); info.AddValue("scope", scope); info.AddValue("role", role); - string objectTypeName = null; - if (objectType is string s) - { - objectTypeName = s; - } - else if (objectType is Type t) - { - objectTypeName = t.AssemblyQualifiedName; - } - info.AddValue("objectTypeName", objectTypeName); + info.AddValue("objectTypeName", objectType.AssemblyQualifiedName); info.AddValue("autowireMode", autowireMode); info.AddValue("dependencyCheck", dependencyCheck); info.AddValue("dependsOn", dependsOn); diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/AbstractObjectFactory.cs b/src/Spring/Spring.Core/Objects/Factory/Support/AbstractObjectFactory.cs index 860c5220..a5750fca 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/AbstractObjectFactory.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/AbstractObjectFactory.cs @@ -1,5 +1,5 @@ /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ using System; using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; @@ -57,15 +58,14 @@ namespace Spring.Objects.Factory.Support { private readonly string name = Guid.NewGuid().ToString(); - public ISet Value + public HashSet Value { get { - ISet set = LogicalThreadContext.GetData(this.name) as ISet; - if (set == null) + if (!(LogicalThreadContext.GetData(name) is HashSet set)) { - set = CreateSet(); - LogicalThreadContext.SetData(this.name, set); + set = new HashSet(); + LogicalThreadContext.SetData(name, set); } return set; } @@ -73,12 +73,7 @@ namespace Spring.Objects.Factory.Support public void Dispose() { - LogicalThreadContext.FreeNamedDataSlot(this.name); - } - - private ISet CreateSet() - { - return new HashedSet(); + LogicalThreadContext.FreeNamedDataSlot(name); } } @@ -115,14 +110,14 @@ namespace Spring.Objects.Factory.Support /// Marker object to be temporarily registered in the singleton cache, /// while instantiating an object (in order to be able to detect circular references). /// - private static readonly object CURRENTLY_IN_CREATION = new Object(); + private static readonly object CurrentlyInCreation = new object(); /// /// Used as value in hashtable that keeps track of singleton names currently in the /// process of being created. Would not be necessary if we created a case insensitive implementation of /// ISet. /// - private static readonly object EMPTYOBJECT = new object(); + private static readonly object EmptyObject = new object(); /// /// The instance for this class. @@ -142,18 +137,17 @@ namespace Spring.Objects.Factory.Support /// /// root object definitons: object name --> Root Object Definition /// - protected SynchronizedHashtable mergedObjectDefinitions = new Spring.Collections.SynchronizedHashtable(); + protected ConcurrentDictionary mergedObjectDefinitions = new ConcurrentDictionary(); /// /// Whether to cache object metadata or rather reobtain it for every access /// private bool cacheObjectMetadata = true; - /// /// Names of object that have already been created at least once /// - private Spring.Collections.Generic.ISet alreadyCreated = new SynchronizedSet(new HashedSet()); + private Collections.Generic.ISet alreadyCreated = new SynchronizedSet(new HashedSet()); /// /// Creates a new instance of the @@ -188,15 +182,15 @@ namespace Spring.Objects.Factory.Support /// protected AbstractObjectFactory(bool caseSensitive) { - this.log = LogManager.GetLogger(this.GetType()); + log = LogManager.GetLogger(GetType()); this.caseSensitive = caseSensitive; - IEqualityComparer comparer = (caseSensitive) ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; - this.aliasMap = new OrderedDictionary(comparer); - this.singletonCache = new OrderedDictionary(comparer); - this.singletonLocks = new OrderedDictionary(comparer); - this.singletonsInCreation = new OrderedDictionary(comparer); - this.prototypesInCreation = new LogicalThreadContextSetVariable(); + var comparer = (caseSensitive) ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; + aliasMap = new OrderedDictionary(comparer); + singletonCache = new OrderedDictionary(comparer); + singletonLocks = new ConcurrentDictionary>(comparer); + singletonsInCreation = new OrderedDictionary(comparer); + prototypesInCreation = new LogicalThreadContextSetVariable(); } [OnDeserializing] @@ -230,20 +224,14 @@ namespace Spring.Objects.Factory.Support /// /// Returns, whether this factory treats object names case sensitive or not. /// - public bool IsCaseSensitive - { - get { return caseSensitive; } - } + public bool IsCaseSensitive => caseSensitive; /// /// Gets the of /// s /// that will be applied to objects created by this factory. /// - public ISet ObjectPostProcessors - { - get { return objectPostProcessors; } - } + public IReadOnlyList ObjectPostProcessors => objectPostProcessors; /// /// Gets the set of classes that will be ignored for autowiring. @@ -254,26 +242,17 @@ namespace Spring.Objects.Factory.Support /// s. ///

/// - public ISet IgnoredDependencyTypes - { - get { return ignoreDependencyTypes; } - } + public ISet IgnoredDependencyTypes => ignoreDependencyTypes; /// /// Returns, whether this object factory instance contains objects. /// - protected bool HasInstantiationAwareBeanPostProcessors - { - get { return hasInstantiationAwareBeanPostProcessors; } - } + protected bool HasInstantiationAwareBeanPostProcessors => hasInstantiationAwareBeanPostProcessors; /// /// Returns, whether this object factory instance contains objects. /// - protected bool HasDestructionAwareBeanPostProcessors - { - get { return hasDestructionAwareBeanPostProcessors; } - } + protected bool HasDestructionAwareBeanPostProcessors => hasDestructionAwareBeanPostProcessors; /// /// Return an instance (possibly shared or independent) of the given object name. @@ -563,12 +542,15 @@ namespace Spring.Objects.Factory.Support protected string TransformedObjectName(string name) { string objectName = ObjectFactoryUtils.TransformedObjectName(name); - // handle aliasing... - lock (aliasMap) + + if (aliasMap.Count > 0) { - string canonicalName = (string)aliasMap[objectName]; - return canonicalName != null ? canonicalName : objectName; + // handle aliasing... + string canonicalName = (string) aliasMap[objectName]; + return canonicalName ?? objectName; } + + return objectName; } /// @@ -596,10 +578,7 @@ namespace Spring.Objects.Factory.Support /// protected bool IsAlias(string name) { - lock (aliasMap) - { - return aliasMap.Contains(name); - } + return aliasMap.Contains(name); } /// @@ -656,19 +635,10 @@ namespace Spring.Objects.Factory.Support return null; } - RootObjectDefinition mod; - // Check with full lock now in order to enforce the same merged instance. - lock (this.mergedObjectDefinitions.SyncRoot) + RootObjectDefinition ValueFactory(string key) { - mod = this.mergedObjectDefinitions[name] as RootObjectDefinition; - - if (null != mod) - { - return mod; - } - - + RootObjectDefinition mod; if (od.ParentName == null) { mod = CreateRootObjectDefinition(od); @@ -676,43 +646,38 @@ namespace Spring.Objects.Factory.Support else { IObjectDefinition pod = null; - if (!name.Equals(od.ParentName)) + if (!key.Equals(od.ParentName)) { pod = GetMergedObjectDefinition(TransformedObjectName(od.ParentName), true); } else { - if (ParentObjectFactory is AbstractObjectFactory) + if (ParentObjectFactory is AbstractObjectFactory factory) { - pod = ((AbstractObjectFactory)ParentObjectFactory).GetMergedObjectDefinition( - od.ParentName, true); + pod = factory.GetMergedObjectDefinition(od.ParentName, true); } } if (pod == null) { - throw new NoSuchObjectDefinitionException(od.ParentName, - string.Format( - "Parent name '{0}' is equal to object name '{1}' - " - + - "cannot be resolved without an AbstractObjectFactory parent.", - od.ParentName, name)); + throw new NoSuchObjectDefinitionException(od.ParentName, $"Parent name '{od.ParentName}' is equal to object name '{key}' - " + "cannot be resolved without an AbstractObjectFactory parent."); } mod = CreateRootObjectDefinition(pod); mod.OverrideFrom(od); } - // Only cache the merged bean definition if we're already about to create an - // instance of the object, or at least have already created an instance before. - if (CacheObjectMetadata && IsObjectEligibleForMetadataCaching(name)) - { - this.mergedObjectDefinitions.Remove(name); - this.mergedObjectDefinitions.Add(name, mod); - } - return mod; - } //release the lock scope + } + + // Only cache the merged bean definition if we're already about to create an + // instance of the object, or at least have already created an instance before. + if (CacheObjectMetadata && IsObjectEligibleForMetadataCaching(name)) + { + return mergedObjectDefinitions.GetOrAdd(name, ValueFactory); + } + + return ValueFactory(name); } /// @@ -728,9 +693,9 @@ namespace Spring.Objects.Factory.Support // Quick check on the concurrent map first, with minimal locking. RootObjectDefinition mbd = null; - if (this.mergedObjectDefinitions.ContainsKey(objectName)) + if (mergedObjectDefinitions.ContainsKey(objectName)) { - mbd = this.mergedObjectDefinitions[objectName] as RootObjectDefinition; + mbd = mergedObjectDefinitions[objectName] as RootObjectDefinition; } return mbd; // ?? GetMergedObjectDefinition(objectName, GetObjectDefinition(objectName)); @@ -743,15 +708,15 @@ namespace Spring.Objects.Factory.Support /// /// true if [is object eligible for metadata caching] [the specified bean name]; otherwise, false. /// - protected bool IsObjectEligibleForMetadataCaching(String beanName) + protected bool IsObjectEligibleForMetadataCaching(string beanName) { - return this.alreadyCreated.Contains(beanName); + return alreadyCreated.Contains(beanName); } protected bool CacheObjectMetadata { - get { return this.cacheObjectMetadata; } - set { this.cacheObjectMetadata = value; } + get => cacheObjectMetadata; + set => cacheObjectMetadata = value; } /// @@ -1230,7 +1195,7 @@ namespace Spring.Objects.Factory.Support AssertUtils.ArgumentHasText(name, "name"); lock (GetSingletonLockFor(name)) { - this.singletonCache.Remove(name); + singletonCache.Remove(name); } } @@ -1425,10 +1390,10 @@ namespace Spring.Objects.Factory.Support if (parentFactory != null && !ContainsObjectDefinition(objectName)) { // No object definition found in this factory -> delegate to parent. - return parentFactory.GetType(this.OriginalObjectName(name)); + return parentFactory.GetType(OriginalObjectName(name)); } - RootObjectDefinition mod = this.GetMergedObjectDefinition(objectName, false); + RootObjectDefinition mod = GetMergedObjectDefinition(objectName, false); Type objectType = PredictObjectType(objectName, mod); if (objectType != null && typeof(IFactoryObject).IsAssignableFrom(objectType)) @@ -1572,7 +1537,7 @@ namespace Spring.Objects.Factory.Support /// /// In the case of object validation errors. /// - protected void CheckMergedObjectDefinition(RootObjectDefinition mergedObjectDefinition, String objectName, + protected void CheckMergedObjectDefinition(RootObjectDefinition mergedObjectDefinition, string objectName, Type requiredType, params object[] arguments) { // check if required type can match according to the object definition; @@ -1621,10 +1586,7 @@ namespace Spring.Objects.Factory.Support /// Gets the temporary object that is placed /// into the singleton cache during object resolution. /// - protected object TemporarySingletonPlaceHolder - { - get { return CURRENTLY_IN_CREATION; } - } + protected object TemporarySingletonPlaceHolder => CurrentlyInCreation; /// /// Parent object factory, for object inheritance support @@ -1635,18 +1597,17 @@ namespace Spring.Objects.Factory.Support /// Dependency types to ignore on dependency check and autowire, as Set of /// Type objects: for example, string. Default is none. /// - private ISet ignoreDependencyTypes = new HybridSet(); - + private HybridSet ignoreDependencyTypes = new HybridSet(); /// /// ObjectPostProcessors to apply in CreateObject /// - private ISet objectPostProcessors = new SortedSet(new ObjectOrderComparator()); + private List objectPostProcessors = new List(); /// /// String Resolver applied to Autowired value injections /// - private ISet embeddedValueResolvers = new SortedSet(new ObjectOrderComparator()); + private SortedSet embeddedValueResolvers = new SortedSet(new ObjectOrderComparator()); /// /// Indicates whether any IInstantiationAwareBeanPostProcessors have been registered @@ -1661,7 +1622,7 @@ namespace Spring.Objects.Factory.Support private bool caseSensitive; private OrderedDictionary aliasMap; private OrderedDictionary singletonCache; - private OrderedDictionary singletonLocks; + private ConcurrentDictionary> singletonLocks; /// /// Set of registered singletons, containing the instance names in registration order @@ -1676,16 +1637,13 @@ namespace Spring.Objects.Factory.Support /// Set that holds all inner objects created by this factory that implement the IDisposable /// interface, to be destroyed on call to Dispose. /// - private ISet disposableInnerObjects = new SynchronizedSet(new HybridSet()); + private SynchronizedSet disposableInnerObjects = new SynchronizedSet(new HybridSet()); /// /// Set that holds all inner objects created by this factory that implement the IDisposable /// interface, to be destroyed on call to Dispose. /// - protected internal ISet DisposableInnerObjects - { - get { return disposableInnerObjects; } - } + protected internal ISet DisposableInnerObjects => disposableInnerObjects; /// /// The parent object factory, or if there is none. @@ -1695,8 +1653,8 @@ namespace Spring.Objects.Factory.Support /// public IObjectFactory ParentObjectFactory { - get { return parentObjectFactory; } - set { parentObjectFactory = value; } + get => parentObjectFactory; + set => parentObjectFactory = value; } /// @@ -1723,7 +1681,7 @@ namespace Spring.Objects.Factory.Support public bool IsSingleton(string name) { string objectName = TransformedObjectName(name); - object objectInstance = this.GetSingleton(objectName); + object objectInstance = GetSingleton(objectName); if (objectInstance != null) { IFactoryObject factoryObject = objectInstance as IFactoryObject; @@ -1796,7 +1754,7 @@ namespace Spring.Objects.Factory.Support { string objectName = TransformedObjectName(name); IObjectFactory parentFactory = ParentObjectFactory; - if (parentFactory != null && !this.ContainsObjectDefinition(objectName)) + if (parentFactory != null && !ContainsObjectDefinition(objectName)) { // No object definition found in this factory -> delegate to parent return parentFactory.IsPrototype(OriginalObjectName(name)); @@ -1841,7 +1799,7 @@ namespace Spring.Objects.Factory.Support return (!ObjectFactoryUtils.IsFactoryDereference(name) || IsFactoryObject(name)); } - IObjectFactory parent = this.ParentObjectFactory; + IObjectFactory parent = ParentObjectFactory; return (parent != null) && parent.ContainsObject(OriginalObjectName(name)); } @@ -1857,17 +1815,15 @@ namespace Spring.Objects.Factory.Support if (isInSingletonCache || ContainsObjectDefinition(objectName)) { // if found, gather aliases... - List matches = new List(); - lock (aliasMap) + var matches = new List(); + foreach (DictionaryEntry aliasEntry in aliasMap) { - foreach (DictionaryEntry aliasEntry in aliasMap) + if (0 == string.Compare((string) aliasEntry.Value, objectName, !IsCaseSensitive)) { - if (0 == string.Compare((string)aliasEntry.Value, objectName, !this.IsCaseSensitive)) - { - matches.Add((string)aliasEntry.Key); - } + matches.Add((string) aliasEntry.Key); } } + return matches; } @@ -1883,10 +1839,7 @@ namespace Spring.Objects.Factory.Support /// Return an instance (possibly shared or independent) of the given object name. /// /// . - public object this[string name] - { - get { return GetObject(name); } - } + public object this[string name] => GetObject(name); /// /// Return an unconfigured(!) instance (possibly shared or independent) of the given object name. @@ -2133,7 +2086,7 @@ namespace Spring.Objects.Factory.Support if (log.IsDebugEnabled) { - log.Debug(string.Format("{2}GetObjectInternal: obtaining instance for name {0} => canonical name {1}", name, objectName, new String(' ', nestingCount * INDENT))); + log.Debug(string.Format("{2}GetObjectInternal: obtaining instance for name {0} => canonical name {1}", name, objectName, new string(' ', nestingCount * INDENT))); } object instance = null; @@ -2154,7 +2107,7 @@ namespace Spring.Objects.Factory.Support } else { - log.Debug(string.Format("Returning cached instance of singleton object '{0}'.", objectName)); + log.Debug($"Returning cached instance of singleton object '{objectName}'."); } } @@ -2245,7 +2198,7 @@ namespace Spring.Objects.Factory.Support hasErrors = true; if (log.IsErrorEnabled) { - log.Error(string.Format("{1}GetObjectInternal: error obtaining object {0}", name, new String(' ', nestingCount * INDENT))); + log.Error(string.Format("{1}GetObjectInternal: error obtaining object {0}", name, new string(' ', nestingCount * INDENT))); } throw; @@ -2264,7 +2217,7 @@ namespace Spring.Objects.Factory.Support if (log.IsDebugEnabled) { - log.Debug(string.Format("{1}GetObjectInternal: returning instance for objectname {0}", name, new String(' ', nestingCount * INDENT))); + log.Debug(string.Format("{1}GetObjectInternal: returning instance for objectname {0}", name, new string(' ', nestingCount * INDENT))); } } } @@ -2393,7 +2346,7 @@ namespace Spring.Objects.Factory.Support log.Debug(string.Format("Destroying singletons in factory [{0}].", this)); } - this.prototypesInCreation.Dispose(); + prototypesInCreation.Dispose(); lock (singletonCache) { @@ -2432,24 +2385,29 @@ namespace Spring.Objects.Factory.Support private void BeforePrototypeCreation(string name) { - this.prototypesInCreation.Value.Add(name); + prototypesInCreation.Value.Add(name); } private void AfterPrototypeCreation(string name) { - if (!IsPrototypeCurrentlyInCreation(name)) + var values = prototypesInCreation.Value; + if (!values.Contains(name)) { - throw new InvalidOperationException("Singleton " + name + " isn't currently in creation."); + ThrowNotCurrentlyInCreation(name); } - this.prototypesInCreation.Value.Remove(name); + values.Remove(name); + } + + private static void ThrowNotCurrentlyInCreation(string name) + { + throw new InvalidOperationException("Singleton " + name + " isn't currently in creation."); } private bool IsPrototypeCurrentlyInCreation(string name) { - return this.prototypesInCreation.Value.Contains(name); + return prototypesInCreation.Value.Contains(name); } - private void AfterSingletonCreation(string name) { if (!IsSingletonCurrentlyInCreation(name)) @@ -2461,16 +2419,16 @@ namespace Spring.Objects.Factory.Support private void BeforeSingletonCreation(string name) { - if (this.singletonsInCreation.Contains(name)) + if (singletonsInCreation.Contains(name)) { throw new ObjectCurrentlyInCreationException(name); } - singletonsInCreation.Add(name, EMPTYOBJECT); + singletonsInCreation.Add(name, EmptyObject); } private bool IsSingletonCurrentlyInCreation(string name) { - return this.singletonsInCreation.Contains(name); + return singletonsInCreation.Contains(name); } /// @@ -2514,9 +2472,9 @@ namespace Spring.Objects.Factory.Support } // ensure the same instance doesn't get registered twice - if (!ObjectPostProcessors.Contains(objectPostProcessor)) + if (!objectPostProcessors.Contains(objectPostProcessor)) { - ObjectPostProcessors.Add(objectPostProcessor); + objectPostProcessors.Add(objectPostProcessor); } if (typeof(IInstantiationAwareObjectPostProcessor).IsInstanceOfType(objectPostProcessor)) { @@ -2537,10 +2495,7 @@ namespace Spring.Objects.Factory.Support /// s. /// /// . - public int ObjectPostProcessorCount - { - get { return ObjectPostProcessors.Count; } - } + public int ObjectPostProcessorCount => objectPostProcessors.Count; /// /// Given an object name, create an alias. @@ -2555,7 +2510,8 @@ namespace Spring.Objects.Factory.Support { if (log.IsDebugEnabled) { - log.Debug(string.Format("Ignoring attempt to Register alias '{0}' for object with name '{1}' because name and alias would be the same value.", alias, name)); + log.Debug( + $"Ignoring attempt to Register alias '{alias}' for object with name '{name}' because name and alias would be the same value."); } return; @@ -2563,21 +2519,17 @@ namespace Spring.Objects.Factory.Support if (log.IsDebugEnabled) { - log.Debug(string.Format("Registering alias '{0}' for object with name '{1}'.", alias, name)); + log.Debug($"Registering alias '{alias}' for object with name '{name}'."); } - lock (aliasMap) + object registeredName = aliasMap[alias]; + if (registeredName != null) { - object registeredName = aliasMap[alias]; - if (registeredName != null) - { - throw new ObjectDefinitionStoreException( - string.Format( - "Cannot register alias '{0}' for object with name '{1}': it's already registered for object name '{2}'.", - alias, name, registeredName)); - } - aliasMap[alias] = name; + throw new ObjectDefinitionStoreException( + $"Cannot register alias '{alias}' for object with name '{name}': it's already registered for object name '{registeredName}'."); } + + aliasMap[alias] = name; } /// @@ -2711,7 +2663,7 @@ namespace Spring.Objects.Factory.Support /// matching the instance name but potentially being a different instance /// (for example, a DisposableBean adapter for a singleton that does not /// naturally implement ). - public void RegisterDisposableObject(String objectName, IDisposable instance) + public void RegisterDisposableObject(string objectName, IDisposable instance) { if (disposableObjects.ContainsKey(objectName)) return; disposableObjects.Add(objectName, instance); @@ -2740,14 +2692,7 @@ namespace Spring.Objects.Factory.Support /// lock object private object GetSingletonLockFor(string objectName) { - lock (singletonLocks) - { - if (!singletonLocks.Contains(objectName)) - { - singletonLocks.Add(objectName, new object()); - } - return singletonLocks[objectName]; - } + return singletonLocks.GetOrAdd(objectName, key => new Lazy(() => new object())).Value; } } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/ChildObjectDefinition.cs b/src/Spring/Spring.Core/Objects/Factory/Support/ChildObjectDefinition.cs index 9d5d006e..278b9ca5 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/ChildObjectDefinition.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/ChildObjectDefinition.cs @@ -1,5 +1,5 @@ /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/ConstructorResolver.cs b/src/Spring/Spring.Core/Objects/Factory/Support/ConstructorResolver.cs index c602d2ad..c2e02bc9 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/ConstructorResolver.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/ConstructorResolver.cs @@ -15,7 +15,6 @@ */ using System; -using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; @@ -94,7 +93,7 @@ namespace Spring.Objects.Factory.Support ConstructorInstantiationInfo constructorInstantiationInfo = GetConstructorInstantiationInfo( objectName, rod, chosenCtors, explicitArgs); - wrapper.WrappedInstance = instantiationStrategy.Instantiate(rod, objectName, this.objectFactory, + wrapper.WrappedInstance = instantiationStrategy.Instantiate(rod, objectName, objectFactory, constructorInstantiationInfo.ConstructorInfo, constructorInstantiationInfo.ArgInstances); if (log.IsDebugEnabled) @@ -381,8 +380,8 @@ namespace Spring.Objects.Factory.Support unsatisfiedDependencyExceptionData = null; ArgumentsHolder args = new ArgumentsHolder(paramTypes.Length); - ISet usedValueHolders = new HybridSet(); - IList autowiredObjectNames = new LinkedList(); + var usedValueHolders = new HybridSet(); + List autowiredObjectNames = null; bool resolveNecessary = false; ParameterInfo[] argTypes = methodOrCtorInfo.GetParameters(); @@ -453,6 +452,7 @@ namespace Spring.Objects.Factory.Support try { MethodParameter param = MethodParameter.ForMethodOrConstructor(methodOrCtorInfo, paramIndex); + autowiredObjectNames = new List(); object autowiredArgument = ResolveAutoWiredArgument(param, objectName, autowiredObjectNames); args.rawArguments[paramIndex] = autowiredArgument; args.arguments[paramIndex] = autowiredArgument; @@ -468,12 +468,14 @@ namespace Spring.Objects.Factory.Support } } - foreach (string autowiredObjectName in autowiredObjectNames) + + if (log.IsDebugEnabled && autowiredObjectNames != null) { - if (log.IsDebugEnabled) + for (var i = 0; i < autowiredObjectNames.Count; i++) { - log.Debug("Autowiring by type from object name '" + objectName + - "' via " + methodType + " to object named '" + autowiredObjectName + "'"); + string autowiredObjectName = autowiredObjectNames[i]; + log.Debug( + $"Autowiring by type from object name '{objectName}' via {methodType} to object named '{autowiredObjectName}'"); } } @@ -486,11 +488,15 @@ namespace Spring.Objects.Factory.Support { } - private object ResolveAutoWiredArgument(MethodParameter methodParameter, string objectName, IList autowiredObjectNames) + private object ResolveAutoWiredArgument( + MethodParameter methodParameter, + string objectName, + List autowiredObjectNames) { - return - this.autowireFactory.ResolveDependency(new DependencyDescriptor(methodParameter, true), objectName, - autowiredObjectNames); + return autowireFactory.ResolveDependency( + new DependencyDescriptor(methodParameter, true), + objectName, + autowiredObjectNames); } /// @@ -609,25 +615,26 @@ namespace Spring.Objects.Factory.Support MemberInfo[] methods = searchType.FindMembers(MemberTypes.Method, methodFlags, new CriteriaMemberFilter().FilterMemberByCriteria, methodCriteria); return methods.Cast().ToArray(); } - internal class ArgumentsHolder + + private class ArgumentsHolder { - public object[] rawArguments; - public object[] arguments; - public object[] preparedArguments; + public readonly object[] rawArguments; + public readonly object[] arguments; + public readonly object[] preparedArguments; public ArgumentsHolder(int size) { - this.rawArguments = new object[size]; - this.arguments = new object[size]; - this.preparedArguments = new object[size]; + rawArguments = new object[size]; + arguments = new object[size]; + preparedArguments = new object[size]; } public ArgumentsHolder(object[] args) { - this.rawArguments = args; - this.arguments = args; - this.preparedArguments = args; + rawArguments = args; + arguments = args; + preparedArguments = args; } public int GetTypeDifferenceWeight(Type[] paramTypes) @@ -636,8 +643,8 @@ namespace Spring.Objects.Factory.Support // Try type difference weight on both the converted arguments and // the raw arguments. If the raw weight is better, use it. // Decrease raw weight by 1024 to prefer it over equal converted weight. - int typeDiffWeight = AutowireUtils.GetTypeDifferenceWeight(paramTypes, this.arguments); - int rawTypeDiffWeight = AutowireUtils.GetTypeDifferenceWeight(paramTypes, this.rawArguments) - 1024; + int typeDiffWeight = AutowireUtils.GetTypeDifferenceWeight(paramTypes, arguments); + int rawTypeDiffWeight = AutowireUtils.GetTypeDifferenceWeight(paramTypes, rawArguments) - 1024; return (rawTypeDiffWeight < typeDiffWeight ? rawTypeDiffWeight : typeDiffWeight); } } diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/DefaultListableObjectFactory.cs b/src/Spring/Spring.Core/Objects/Factory/Support/DefaultListableObjectFactory.cs index 3cdabf48..d8b73b04 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/DefaultListableObjectFactory.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/DefaultListableObjectFactory.cs @@ -17,11 +17,8 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Collections.Specialized; using System.Globalization; -using Common.Logging; - using Spring.Core; using Spring.Core.TypeConversion; using Spring.Objects.Factory.Config; @@ -476,7 +473,7 @@ namespace Spring.Objects.Factory.Support "Value [" + autowiredValue + "] does not implement specified type [" + dependencyType.Name + "]"); if (!resolvableDependencies.ContainsKey(dependencyType)) { - this.resolvableDependencies.Add(dependencyType, autowiredValue); + resolvableDependencies.Add(dependencyType, autowiredValue); } } } @@ -1089,13 +1086,15 @@ namespace Spring.Objects.Factory.Support /// The descriptor for the dependency. /// Name of the object which declares the present dependency. /// A list that all names of autowired object (used for - /// resolving the present dependency) are supposed to be added to. + /// resolving the present dependency) are supposed to be added to. /// /// the resolved object, or null if none found /// /// if dependency resolution failed - public override object ResolveDependency(DependencyDescriptor descriptor, string objectName, - IList autowiredObjectNames) + public override object ResolveDependency( + DependencyDescriptor descriptor, + string objectName, + IList autowiredObjectNames) { Type type = descriptor.DependencyType; Object value = AutowireCandidateResolver.GetSuggestedValue(descriptor); @@ -1114,7 +1113,7 @@ namespace Spring.Objects.Factory.Support if (type.IsArray) { Type elementType = type.GetElementType(); - IDictionary matchingObjects = FindAutowireCandidates(objectName, elementType, descriptor); + var matchingObjects = FindAutowireCandidates(objectName, elementType, descriptor); if (matchingObjects.Count == 0) { if (descriptor.Required) @@ -1125,7 +1124,7 @@ namespace Spring.Objects.Factory.Support } if (autowiredObjectNames != null) { - foreach (DictionaryEntry matchingObject in matchingObjects) + foreach (var matchingObject in matchingObjects) { autowiredObjectNames.Add(matchingObject.Key); } @@ -1143,7 +1142,7 @@ namespace Spring.Objects.Factory.Support throw new NoSuchObjectDefinitionException(type, "expected first generic to be a string but is " + type.GetGenericArguments()[0]); - IDictionary matchingObjects = FindAutowireCandidates(objectName, elementType, descriptor); + var matchingObjects = FindAutowireCandidates(objectName, elementType, descriptor); if (matchingObjects.Count == 0) { if (descriptor.Required) @@ -1154,7 +1153,7 @@ namespace Spring.Objects.Factory.Support } if (autowiredObjectNames != null) { - foreach (DictionaryEntry matchingObject in matchingObjects) + foreach (var matchingObject in matchingObjects) { autowiredObjectNames.Add(matchingObject.Key); } @@ -1172,7 +1171,7 @@ namespace Spring.Objects.Factory.Support } else { - IDictionary matchingObjects = FindAutowireCandidates(objectName, type, descriptor); + var matchingObjects = FindAutowireCandidates(objectName, type, descriptor); if (matchingObjects.Count == 0) { if (descriptor.Required) @@ -1192,17 +1191,12 @@ namespace Spring.Objects.Factory.Support throw new NoSuchObjectDefinitionException(type, "expected single matching object but found " + matchingObjects.Count + ": " + matchingObjects); } - if (autowiredObjectNames != null) - { - autowiredObjectNames.Add(primaryObjecName); - } + + autowiredObjectNames?.Add(primaryObjecName); return matchingObjects[primaryObjecName]; } - DictionaryEntry entry = (DictionaryEntry)ObjectUtils.EnumerateFirstElement(matchingObjects); - if (autowiredObjectNames != null) - { - autowiredObjectNames.Add(entry.Key); - } + var entry = (KeyValuePair) ObjectUtils.EnumerateFirstElement(matchingObjects); + autowiredObjectNames?.Add(entry.Key); return entry.Value; } } @@ -1289,18 +1283,18 @@ namespace Spring.Objects.Factory.Support "expected at least 1 object which qualifies as autowire candidate for this dependency. "); } - private IDictionary FindAutowireCandidates(string objectName, Type requiredType, DependencyDescriptor descriptor) + private Dictionary FindAutowireCandidates(string objectName, Type requiredType, DependencyDescriptor descriptor) { IList candidateNames = ObjectFactoryUtils.ObjectNamesForTypeIncludingAncestors(this, requiredType, true, descriptor.Eager); - IDictionary result = new OrderedDictionary(candidateNames.Count); + var result = new Dictionary(candidateNames.Count); foreach (var entry in resolvableDependencies) { Type autoWiringType = entry.Key; if (autoWiringType.IsAssignableFrom(requiredType)) { - object autowiringValue = this.resolvableDependencies[autoWiringType]; + object autowiringValue = resolvableDependencies[autoWiringType]; if (requiredType.IsInstanceOfType(autowiringValue)) { result.Add(ObjectUtils.IdentityToString(autowiringValue), autowiringValue); diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/DisposableObjectAdapter.cs b/src/Spring/Spring.Core/Objects/Factory/Support/DisposableObjectAdapter.cs index 44c21e6a..4c9b5c0f 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/DisposableObjectAdapter.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/DisposableObjectAdapter.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using Common.Logging; -using Spring.Collections; using Spring.Objects.Factory.Config; using Spring.Util; @@ -32,7 +31,7 @@ namespace Spring.Objects.Factory.Support /// Name of the bean. /// The merged bean definition. /// the List of BeanPostProcessors (potentially IDestructionAwareBeanPostProcessor), if any. - public DisposableObjectAdapter(object instance, string objectName, RootObjectDefinition objectDefinition, ISet postProcessors) + public DisposableObjectAdapter(object instance, string objectName, RootObjectDefinition objectDefinition, IReadOnlyCollection postProcessors) { AssertUtils.ArgumentNotNull(instance, "Disposable object must not be null"); @@ -104,7 +103,7 @@ namespace Spring.Objects.Factory.Support /// /// The List to search. /// the filtered List of IDestructionAwareObjectPostProcessors. - private List FilterPostProcessors(ISet postProcessors) + private List FilterPostProcessors(IReadOnlyCollection postProcessors) { List filteredPostProcessors = null; if (postProcessors != null && postProcessors.Count != 0) @@ -115,8 +114,6 @@ namespace Spring.Objects.Factory.Support return filteredPostProcessors; } - - /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/IConfigurableObjectDefinition.cs b/src/Spring/Spring.Core/Objects/Factory/Support/IConfigurableObjectDefinition.cs index 35429241..cbdcb424 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/IConfigurableObjectDefinition.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/IConfigurableObjectDefinition.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -161,7 +161,7 @@ namespace Spring.Objects.Factory.Support /// preparation on startup. ///

/// - new IList DependsOn { get; set; } + new IReadOnlyList DependsOn { get; set; } /// /// The name of the initializer method. diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/MethodOverride.cs b/src/Spring/Spring.Core/Objects/Factory/Support/MethodOverride.cs index c198cfa3..dd8191c5 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/MethodOverride.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/MethodOverride.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/MethodOverrides.cs b/src/Spring/Spring.Core/Objects/Factory/Support/MethodOverrides.cs index c037759b..c0a76996 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/MethodOverrides.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/MethodOverrides.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +14,11 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Collections; +using System.Collections.Generic; +using System.Linq; using System.Reflection; -using Spring.Collections; - -#endregion namespace Spring.Objects.Factory.Support { @@ -36,9 +29,11 @@ namespace Spring.Objects.Factory.Support /// Rod Johnson /// Rick Evans [Serializable] - public class MethodOverrides : IEnumerable + public class MethodOverrides : IEnumerable { - #region Constructor (s) / Destructor + private HashSet _overrides; + + private HashSet _overloadedMethodNames; /// /// Creates a new instance of the @@ -65,29 +60,10 @@ namespace Spring.Objects.Factory.Support AddAll(other); } - #endregion - - #region Properties - - /// - /// The collection of method overrides. - /// - public ISet Overrides - { - get { return _overrides; } - } - /// /// Returns true if this instance contains no overrides. /// - public bool IsEmpty - { - get { return Overrides.IsEmpty; } - } - - #endregion - - #region Methods + public bool IsEmpty => _overrides== null || _overrides.Count == 0; /// /// Copy all given method overrides into this object. @@ -99,8 +75,23 @@ namespace Spring.Objects.Factory.Support { if (other != null) { - Overrides.AddAll(other.Overrides); - _overloadedMethodNames.AddAll(other._overloadedMethodNames); + if (other._overrides != null && other._overrides.Count > 0) + { + _overrides = _overrides ?? new HashSet(); + foreach (var @override in other._overrides) + { + _overrides.Add(@override); + } + } + + if (other._overloadedMethodNames != null && other._overloadedMethodNames.Count > 0) + { + _overloadedMethodNames = _overloadedMethodNames ?? new HashSet(); + foreach (var methodName in other._overloadedMethodNames) + { + _overloadedMethodNames.Add(methodName); + } + } } } @@ -114,7 +105,8 @@ namespace Spring.Objects.Factory.Support /// public void Add(MethodOverride theOverride) { - Overrides.Add(theOverride); + _overrides = _overrides ?? new HashSet(); + _overrides.Add(theOverride); } /// @@ -126,6 +118,7 @@ namespace Spring.Objects.Factory.Support /// public void AddOverloadedMethodName(string methodName) { + _overloadedMethodNames = _overloadedMethodNames ?? new HashSet(); _overloadedMethodNames.Add(methodName); } @@ -142,7 +135,7 @@ namespace Spring.Objects.Factory.Support /// public bool IsOverloadedMethodName(string methodName) { - return _overloadedMethodNames.Contains(methodName); + return _overloadedMethodNames != null && _overloadedMethodNames.Contains(methodName); } /// @@ -156,44 +149,31 @@ namespace Spring.Objects.Factory.Support /// public MethodOverride GetOverride(MethodInfo method) { - foreach (MethodOverride ovr in Overrides) + if (_overrides == null) + { + return null; + } + foreach (MethodOverride ovr in _overrides) { if (ovr.Matches(method)) { return ovr; } } + return null; } - /// - /// Returns an that can iterate - /// through a collection. - /// - /// - ///

- /// The returned is the - /// exposed by the - /// - /// property. - ///

- ///
- /// - /// An that can iterate through a - /// collection. - /// - public IEnumerator GetEnumerator() + /// + public IEnumerator GetEnumerator() { - return Overrides.GetEnumerator(); + return _overrides?.GetEnumerator() ?? Enumerable.Empty().GetEnumerator(); } - #endregion - - #region Fields - - private ISet _overrides = new HybridSet(); - private ISet _overloadedMethodNames = new HybridSet(); - - #endregion + /// + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionBuilder.cs b/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionBuilder.cs index bbfa599a..c9f84e18 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionBuilder.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionBuilder.cs @@ -1,5 +1,3 @@ -#region License - /* * Copyright 2002-2010 the original author or authors. * @@ -16,13 +14,9 @@ * limitations under the License. */ -#endregion - -#region Imports using System; -using System.Collections.Generic; +using System.Collections.Generic; using Spring.Objects.Factory.Config; -#endregion namespace Spring.Objects.Factory.Support { @@ -38,17 +32,12 @@ namespace Spring.Objects.Factory.Support /// Mark Pollack (.NET) public class ObjectDefinitionBuilder { - #region Fields private AbstractObjectDefinition objectDefinition; private IObjectDefinitionFactory objectDefinitionFactory; private int constructorArgIndex; - #endregion - - #region Constructor(s) - /// /// Initializes a new instance of the class, private /// to force use of factory methods. @@ -57,42 +46,38 @@ namespace Spring.Objects.Factory.Support { } - #endregion - - #region Factory Methods - - /// - /// Creates a new used to construct a . - /// + /// + /// Creates a new used to construct a . + /// public static ObjectDefinitionBuilder GenericObjectDefinition() - { - ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); - builder.objectDefinition = new GenericObjectDefinition(); - return builder; + { + ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); + builder.objectDefinition = new GenericObjectDefinition(); + return builder; } - /// - /// Creates a new used to construct a . - /// - /// the of the object that the definition is being created for + /// + /// Creates a new used to construct a . + /// + /// the of the object that the definition is being created for public static ObjectDefinitionBuilder GenericObjectDefinition(Type objectType) - { - ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); - builder.objectDefinition = new GenericObjectDefinition(); - builder.objectDefinition.ObjectType = objectType; - return builder; + { + ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); + builder.objectDefinition = new GenericObjectDefinition(); + builder.objectDefinition.ObjectType = objectType; + return builder; } - /// - /// Creates a new used to construct a . - /// - /// the name of the of the object that the definition is being created for + /// + /// Creates a new used to construct a . + /// + /// the name of the of the object that the definition is being created for public static ObjectDefinitionBuilder GenericObjectDefinition(string objectTypeName) - { - ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); - builder.objectDefinition = new GenericObjectDefinition(); - builder.objectDefinition.ObjectTypeName = objectTypeName; - return builder; + { + ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); + builder.objectDefinition = new GenericObjectDefinition(); + builder.objectDefinition.ObjectTypeName = objectTypeName; + return builder; } /// @@ -185,10 +170,6 @@ namespace Spring.Objects.Factory.Support return builder; } - #endregion - - - #region Properties /// /// Gets the current object definition in its raw (unvalidated) form. @@ -214,9 +195,6 @@ namespace Spring.Objects.Factory.Support } - #endregion - - #region Methods //TODO add expression support. /// @@ -335,26 +313,26 @@ namespace Spring.Objects.Factory.Support return this; } - /// - /// Sets the autowire candidate value for this definition. - /// - /// The autowire candidate value + /// + /// Sets the autowire candidate value for this definition. + /// + /// The autowire candidate value /// - public ObjectDefinitionBuilder SetAutowireCandidate(bool autowireCandidate) - { - objectDefinition.IsAutowireCandidate = autowireCandidate; - return this; + public ObjectDefinitionBuilder SetAutowireCandidate(bool autowireCandidate) + { + objectDefinition.IsAutowireCandidate = autowireCandidate; + return this; } - /// - /// Sets the primary value for this definition. - /// - /// If object is primary + /// + /// Sets the primary value for this definition. + /// + /// If object is primary /// - public ObjectDefinitionBuilder SetPrimary(bool primary) - { - objectDefinition.IsPrimary = primary; - return this; + public ObjectDefinitionBuilder SetPrimary(bool primary) + { + objectDefinition.IsPrimary = primary; + return this; } /// @@ -411,18 +389,16 @@ namespace Spring.Objects.Factory.Support { if (objectDefinition.DependsOn == null) { - objectDefinition.DependsOn = new string[] {objectName}; + objectDefinition.DependsOn = new[] {objectName}; } else - { - List arrayList = new List(); - arrayList.AddRange(objectDefinition.DependsOn); - arrayList.AddRange(new string[]{ objectName}); - objectDefinition.DependsOn = arrayList; + { + var list = new List(objectDefinition.DependsOn.Count + 1); + list.AddRange(objectDefinition.DependsOn); + list.Add(objectName); + objectDefinition.DependsOn = list; } return this; } - - #endregion } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionReaderUtils.cs b/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionReaderUtils.cs index 613e33b4..38577c4c 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionReaderUtils.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionReaderUtils.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ namespace Spring.Objects.Factory.Support /// time that the name becomes unique. ///

/// - public const string GENERATED_OBJECT_NAME_SEPARATOR = ObjectFactoryUtils.GENERATED_OBJECT_NAME_SEPARATOR; + public const string GENERATED_OBJECT_NAME_SEPARATOR = ObjectFactoryUtils.GeneratedObjectNameSeparator; /// /// Registers the supplied with the diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionValueResolver.cs b/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionValueResolver.cs index b8b517ef..c1e9299f 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionValueResolver.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionValueResolver.cs @@ -326,7 +326,7 @@ namespace Spring.Objects.Factory.Support while (this.objectFactory.IsObjectNameInUse(actualInnerObjectName)) { counter++; - actualInnerObjectName = innerObjectName + ObjectFactoryUtils.GENERATED_OBJECT_NAME_SEPARATOR + counter; + actualInnerObjectName = innerObjectName + ObjectFactoryUtils.GeneratedObjectNameSeparator + counter; } return actualInnerObjectName; } diff --git a/src/Spring/Spring.Core/Objects/Factory/Support/RootObjectDefinition.cs b/src/Spring/Spring.Core/Objects/Factory/Support/RootObjectDefinition.cs index 6ea6566e..ba63e5a6 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Support/RootObjectDefinition.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Support/RootObjectDefinition.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -268,10 +268,7 @@ namespace Spring.Objects.Factory.Support /// Raised on any attempt to set a non-null value on this property. public override string ParentName { - get - { - return null; - } + get => null; set { if (value != null) @@ -312,7 +309,7 @@ namespace Spring.Objects.Factory.Support /// public override string ToString() { - return String.Format("{0} : {1}", GetType().Name, base.ToString()); + return $"{GetType().Name} : {base.ToString()}"; } } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectDefinitionConstants.cs b/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectDefinitionConstants.cs index 7158d3b3..929b017e 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectDefinitionConstants.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectDefinitionConstants.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Objects/IPropertyValues.cs b/src/Spring/Spring.Core/Objects/IPropertyValues.cs index f9876ac3..c885a28c 100644 --- a/src/Spring/Spring.Core/Objects/IPropertyValues.cs +++ b/src/Spring/Spring.Core/Objects/IPropertyValues.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,63 +28,62 @@ using System.Collections.Generic; namespace Spring.Objects { /// - /// A collection style container for - /// instances. + /// A collection style container for + /// instances. /// /// Rod Johnson /// Mark Pollack (.NET) public interface IPropertyValues : IEnumerable { /// - /// Return an array of the objects - /// held in this object. + /// Return an array of the objects + /// held in this object. + /// /// - /// An array of the objects held - /// in this object. + /// An array of the objects held + /// in this object. /// - IList PropertyValues - { - get; - } - + IReadOnlyList PropertyValues { get; } + /// - /// Return the instance with the - /// given name. + /// Return the instance with the + /// given name. /// /// The name to search for. - /// the , or null if a - /// the with the supplied - /// did not exist in this collection. + /// + /// the , or null if a + /// the with the supplied + /// did not exist in this collection. /// PropertyValue GetPropertyValue(string propertyName); - + /// - /// Is there a instance for this - /// property name? + /// Is there a instance for this + /// property name? /// /// The name to search for. /// - /// True if there is a instance for - /// the supplied . + /// True if there is a instance for + /// the supplied . /// bool Contains(string propertyName); - + /// - /// Return the difference (changes, additions, but not removals) of - /// property values between the supplied argument and the values - /// contained in the collection. + /// Return the difference (changes, additions, but not removals) of + /// property values between the supplied argument and the values + /// contained in the collection. /// /// - ///

- /// Subclasses should also override Equals. - ///

+ ///

+ /// Subclasses should also override Equals. + ///

///
/// The old property values. /// - /// An containing any changes, or - /// an empty instance if there were - /// no changes. + /// An containing any changes, or + /// an empty instance if there were + /// no changes. /// - IPropertyValues ChangesSince (IPropertyValues old); + IPropertyValues ChangesSince(IPropertyValues old); } -} +} \ No newline at end of file diff --git a/src/Spring/Spring.Core/Objects/MutablePropertyValues.cs b/src/Spring/Spring.Core/Objects/MutablePropertyValues.cs index 4583bd74..1c7dbdae 100644 --- a/src/Spring/Spring.Core/Objects/MutablePropertyValues.cs +++ b/src/Spring/Spring.Core/Objects/MutablePropertyValues.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +14,6 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Collections; using System.Collections.Generic; @@ -27,8 +21,6 @@ using System.Globalization; using System.Text; using Spring.Util; -#endregion - namespace Spring.Objects { /// @@ -49,16 +41,8 @@ namespace Spring.Objects [Serializable] public class MutablePropertyValues : IPropertyValues { - #region Fields - - /// - /// The list of objects. - /// - private List propertyValuesList = new List(); - - #endregion - - #region Constructor (s) / Destructor + private static readonly IReadOnlyList emptyPropertyValuesList = new List(); + private List propertyValuesList; /// /// Creates a new instance of the @@ -77,10 +61,10 @@ namespace Spring.Objects /// /// /// - public MutablePropertyValues () + public MutablePropertyValues() { } - + /// /// Creates a new instance of the /// class. @@ -92,7 +76,7 @@ namespace Spring.Objects /// referenced by individual objects. ///

/// - public MutablePropertyValues (IPropertyValues other) + public MutablePropertyValues(IPropertyValues other) { if (other != null) { @@ -108,26 +92,15 @@ namespace Spring.Objects /// The with property values /// keyed by property name, which must be a . /// - public MutablePropertyValues (IDictionary map) + public MutablePropertyValues(IReadOnlyDictionary map) { - AddAll (map); + AddAll(map); } - #endregion - - #region Properties - /// /// Property to retrieve the array of property values. /// - public IList PropertyValues - { - get { return propertyValuesList; } - } - - #endregion - - #region Methods + public IReadOnlyList PropertyValues => propertyValuesList ?? emptyPropertyValuesList; /// /// Overloaded version of Add that takes a property name and a property value. @@ -138,9 +111,9 @@ namespace Spring.Objects /// /// The value of the property. /// - public void Add (string propertyName, object propertyValue) + public void Add(string propertyName, object propertyValue) { - Add (new PropertyValue (propertyName, propertyValue)); + Add(new PropertyValue(propertyName, propertyValue)); } /// @@ -150,19 +123,22 @@ namespace Spring.Objects /// /// The object to add. /// - public void Add (PropertyValue pv) + public void Add(PropertyValue pv) { + propertyValuesList = propertyValuesList ?? new List(); + for (int i = 0; i < propertyValuesList.Count; ++i) { - PropertyValue currentPv = propertyValuesList [i]; - if (currentPv.Name.Equals (pv.Name)) + PropertyValue currentPv = propertyValuesList[i]; + if (currentPv.Name == pv.Name) { pv = MergeIfRequired(pv, currentPv); propertyValuesList[i] = pv; - return ; + return; } } - propertyValuesList.Add (pv); + + propertyValuesList.Add(pv); } /// @@ -176,8 +152,7 @@ namespace Spring.Objects private PropertyValue MergeIfRequired(PropertyValue newPv, PropertyValue currentPv) { object val = newPv.Value; - IMergable mergable = val as IMergable; - if (mergable != null) + if (val is IMergable mergable) { if (mergable.MergeEnabled) { @@ -185,6 +160,7 @@ namespace Spring.Objects return new PropertyValue(newPv.Name, merged); } } + return newPv; } @@ -196,17 +172,37 @@ namespace Spring.Objects /// The map of property values, the keys of which must be /// s. /// - public void AddAll (IDictionary map) + public void AddAll(IReadOnlyDictionary map) { - if (map != null) + if (map != null) { - foreach (KeyValuePair pair in map) + foreach (KeyValuePair pair in map) { - Add (new PropertyValue (pair.Key, pair.Value)); + Add(new PropertyValue(pair.Key, pair.Value)); } } } + /// + /// Add all property values from the given + /// . + /// + /// + /// The map of property values, the keys of which must be + /// s. + /// + public void AddAll(IDictionary map) + { + if (map != null) + { + foreach (KeyValuePair pair in map) + { + Add(new PropertyValue(pair.Key, pair.Value)); + } + } + } + + /// /// Add all property values from the given /// . @@ -214,47 +210,48 @@ namespace Spring.Objects /// /// The list of s to be added. /// - public void AddAll(IList values) + public void AddAll(IReadOnlyList values) { - if (values != null) + if (values != null) { - foreach (PropertyValue value in values) + for (var i = 0; i < values.Count; i++) { - Add (value); + Add(values[i]); } } } - + /// /// Remove the given , if contained. /// /// /// The to remove. /// - public void Remove (PropertyValue pv) + public void Remove(PropertyValue pv) { - propertyValuesList.Remove (pv); + propertyValuesList?.Remove(pv); } - + /// /// Removes the named , if contained. /// /// /// The name of the property. /// - public void Remove (string propertyName) + public void Remove(string propertyName) { - Remove (GetPropertyValue (propertyName)); + Remove(GetPropertyValue(propertyName)); } - + /// /// Modify a object held in this object. Indexed from 0. /// - public void SetPropertyValueAt (PropertyValue pv, int i) + public void SetPropertyValueAt(PropertyValue pv, int i) { - propertyValuesList [i] = pv; + propertyValuesList = propertyValuesList ?? new List(); + propertyValuesList[i] = pv; } - + /// /// Return the property value given the name. /// @@ -267,19 +264,26 @@ namespace Spring.Objects /// /// The property value. /// - public PropertyValue GetPropertyValue (string propertyName) + public PropertyValue GetPropertyValue(string propertyName) { - string propertyNameLowered = propertyName.ToLower (CultureInfo.CurrentCulture); - foreach (PropertyValue pv in propertyValuesList) + if (propertyValuesList == null) { - if (pv.Name.ToLower(CultureInfo.CurrentCulture).Equals (propertyNameLowered)) + return null; + } + + string propertyNameLowered = propertyName.ToLower(CultureInfo.CurrentCulture); + for (var i = 0; i < propertyValuesList.Count; i++) + { + PropertyValue pv = propertyValuesList[i]; + if (pv.Name.ToLower(CultureInfo.CurrentCulture).Equals(propertyNameLowered)) { return pv; } } + return null; } - + /// /// Does the container of properties contain one of this name. /// @@ -287,11 +291,11 @@ namespace Spring.Objects /// /// True if the property is contained in this collection, false otherwise. /// - public bool Contains (string propertyName) + public bool Contains(string propertyName) { - return GetPropertyValue (propertyName) != null; + return GetPropertyValue(propertyName) != null; } - + /// /// Return the difference (changes, additions, but not removals) of /// property values between the supplied argument and the values @@ -301,28 +305,30 @@ namespace Spring.Objects /// /// The collection of property values that are different than the supplied one. /// - public IPropertyValues ChangesSince (IPropertyValues old) + public IPropertyValues ChangesSince(IPropertyValues old) { - MutablePropertyValues changes = new MutablePropertyValues (); - if (old == this) + var changes = new MutablePropertyValues(); + if (old == this || propertyValuesList == null) { return changes; - } + } + // for each property value in this (the newer set) foreach (PropertyValue newProperty in propertyValuesList) { - PropertyValue oldProperty = old.GetPropertyValue (newProperty.Name); + PropertyValue oldProperty = old.GetPropertyValue(newProperty.Name); if (oldProperty == null) { // if there wasn't an old one, add it - changes.Add (newProperty); + changes.Add(newProperty); } - else if (!oldProperty.Equals (newProperty)) + else if (!oldProperty.Equals(newProperty)) { // it's changed - changes.Add (newProperty); + changes.Add(newProperty); } } + return changes; } @@ -342,11 +348,11 @@ namespace Spring.Objects /// An that can iterate through a /// collection. /// - public IEnumerator GetEnumerator () + public IEnumerator GetEnumerator() { - return PropertyValues.GetEnumerator (); + return PropertyValues.GetEnumerator(); } - + // CLOVER:OFF /// @@ -355,18 +361,16 @@ namespace Spring.Objects /// /// A string representation of the object. /// - public override string ToString () + public override string ToString() { - IList pvs = PropertyValues; + var pvs = PropertyValues; StringBuilder sb - = new StringBuilder ( - "MutablePropertyValues: length=").Append (pvs.Count).Append ("; "); - sb.Append (StringUtils.ArrayToDelimitedString (pvs, ",")); - return sb.ToString (); + = new StringBuilder( + "MutablePropertyValues: length=").Append(pvs.Count).Append("; "); + sb.Append(StringUtils.ArrayToDelimitedString(pvs, ",")); + return sb.ToString(); } // CLOVER:ON - - #endregion } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Proxy/AbstractProxyTypeBuilder.cs b/src/Spring/Spring.Core/Proxy/AbstractProxyTypeBuilder.cs index ea861e29..6167b40f 100644 --- a/src/Spring/Spring.Core/Proxy/AbstractProxyTypeBuilder.cs +++ b/src/Spring/Spring.Core/Proxy/AbstractProxyTypeBuilder.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Util/ArrayUtils.cs b/src/Spring/Spring.Core/Util/ArrayUtils.cs index 00851572..2e9dc7a1 100644 --- a/src/Spring/Spring.Core/Util/ArrayUtils.cs +++ b/src/Spring/Spring.Core/Util/ArrayUtils.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,11 +41,17 @@ namespace Spring.Util /// true if the collection has a length and contains only non-null elements. public static bool HasElements(ICollection collection) { - if (!HasLength(collection)) return false; - IEnumerator it = collection.GetEnumerator(); - while(it.MoveNext()) + if (!HasLength(collection)) { - if (it.Current == null ) return false; + return false; + } + + foreach (var item in collection) + { + if (item == null) + { + return false; + } } return true; } @@ -72,7 +78,7 @@ namespace Spring.Util /// public static bool HasLength(ICollection collection) { - return !( (collection == null) || (collection.Count == 0) ); + return collection != null && collection.Count > 0; } /// diff --git a/src/Spring/Spring.Core/Util/AssertUtils.cs b/src/Spring/Spring.Core/Util/AssertUtils.cs index f2f506d2..d7aa49cb 100644 --- a/src/Spring/Spring.Core/Util/AssertUtils.cs +++ b/src/Spring/Spring.Core/Util/AssertUtils.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,16 +18,11 @@ #endregion -#region Imports - using System; using System.Collections; -using System.Globalization; using System.Reflection; using System.Runtime.Remoting; -#endregion - namespace Spring.Util { /// @@ -40,7 +35,7 @@ namespace Spring.Util /// /// Aleksandar Seovic /// Erich Eichinger - public sealed class AssertUtils + public static class AssertUtils { /// /// Checks, whether may be invoked on . @@ -57,21 +52,23 @@ namespace Spring.Util /// public static void Understands(object target, string targetName, MethodBase method) { - ArgumentNotNull(method, "method"); - - if (target==null ) - { - if (method.IsStatic) - { - return; - } - throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Target '{0}' is null and target method '{1}.{2}' is not static.", targetName, method.DeclaringType.FullName, method.Name)); - } + ArgumentNotNull(method, "method"); - Understands(target, targetName, method.DeclaringType); + if (target == null) + { + if (method.IsStatic) + { + return; + } + + ThrowNotSupportedException( + $"Target '{targetName}' is null and target method '{method.DeclaringType.FullName}.{method.Name}' is not static."); + } + + Understands(target, targetName, method.DeclaringType); } - /// + /// /// checks, whether supports the methods of . /// Supports testing transparent proxies. /// @@ -91,7 +88,7 @@ namespace Spring.Util if (target == null) { - throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Target '{0}' is null.", targetName)); + ThrowNotSupportedException($"Target '{targetName}' is null."); } Type targetType = null; @@ -106,7 +103,8 @@ namespace Spring.Util { return; } - throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Target '{0}' is a transparent proxy that does not support methods of '{1}'.", targetName, requiredType.FullName)); + ThrowNotSupportedException( + $"Target '{targetName}' is a transparent proxy that does not support methods of '{requiredType.FullName}'."); } targetType = rp.GetProxiedType(); #endif @@ -118,48 +116,11 @@ namespace Spring.Util if (!requiredType.IsAssignableFrom(targetType)) { - throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Target '{0}' of type '{1}' does not support methods of '{2}'.", targetName, targetType, requiredType.FullName)); + ThrowNotSupportedException($"Target '{targetName}' of type '{targetType}' does not support methods of '{requiredType.FullName}'."); } } - #region checking casts on transparent proxies (From BCL via Reflector) - // private static bool CheckCast(RealProxy rp, Type castType) -// { -// bool flag = false; -// if (castType == typeof(object)) -// { -// return true; -// } -// if (!castType.IsInterface && !castType.IsMarshalByRef) -// { -// return false; -// } -// if (castType != typeof(IObjectReference)) -// { -// IRemotingTypeInfo typeInfo = rp as IRemotingTypeInfo; -// if (typeInfo != null) -// { -// return typeInfo.CanCastTo(castType, rp.GetTransparentProxy()); -// } -// Identity identityObject = rp.IdentityObject; -// if (identityObject != null) -// { -// ObjRef objectRef = identityObject.ObjectRef; -// if (objectRef != null) -// { -// typeInfo = objectRef.TypeInfo; -// if (typeInfo != null) -// { -// flag = typeInfo.CanCastTo(castType, rp.GetTransparentProxy()); -// } -// } -// } -// } -// return flag; - // } - #endregion - - /// + /// /// Checks the value of the supplied and throws an /// if it is . /// @@ -172,11 +133,7 @@ namespace Spring.Util { if (argument == null) { - throw new ArgumentNullException ( - name, - string.Format ( - CultureInfo.InvariantCulture, - "Argument '{0}' cannot be null.", name)); + ThrowArgumentNullException(name); } } @@ -197,7 +154,7 @@ namespace Spring.Util { if (argument == null) { - throw new ArgumentNullException(name, message); + ThrowArgumentNullException(name, message); } } @@ -216,11 +173,9 @@ namespace Spring.Util { if (StringUtils.IsNullOrEmpty(argument)) { - throw new ArgumentNullException ( + ThrowArgumentNullException( name, - string.Format ( - CultureInfo.InvariantCulture, - "Argument '{0}' cannot be null or resolve to an empty string : '{1}'.", name, argument)); + $"Argument '{name}' cannot be null or resolve to an empty string : '{argument}'."); } } @@ -243,7 +198,7 @@ namespace Spring.Util { if (StringUtils.IsNullOrEmpty(argument)) { - throw new ArgumentNullException(name, message); + ThrowArgumentNullException(name, message); } } @@ -261,11 +216,9 @@ namespace Spring.Util { if (!ArrayUtils.HasLength(argument)) { - throw new ArgumentNullException( + ThrowArgumentNullException( name, - string.Format( - CultureInfo.InvariantCulture, - "Argument '{0}' cannot be null or resolve to an empty array", name)); + $"Argument '{name}' cannot be null or resolve to an empty array"); } } @@ -284,7 +237,7 @@ namespace Spring.Util { if(!ArrayUtils.HasLength(argument)) { - throw new ArgumentNullException(name, message); + ThrowArgumentNullException(name, message); } } @@ -302,15 +255,12 @@ namespace Spring.Util { if (!ArrayUtils.HasElements(argument)) { - throw new ArgumentException( + ThrowArgumentException( name, - string.Format( - CultureInfo.InvariantCulture, - "Argument '{0}' must not be null or resolve to an empty collection and must contain non-null elements", name)); + $"Argument '{name}' must not be null or resolve to an empty collection and must contain non-null elements"); } } - /// /// Checks whether the specified can be cast /// into the . @@ -330,14 +280,13 @@ namespace Spring.Util /// public static void AssertArgumentType(object argument, string argumentName, Type requiredType, string message) { - if (argument != null && requiredType != null && !requiredType.IsAssignableFrom(argument.GetType())) + if (argument != null && requiredType != null && !requiredType.IsInstanceOfType(argument)) { - throw new ArgumentException(message, argumentName); + ThrowArgumentException(message, argumentName); } } - - /// + /// /// Assert a boolean expression, throwing ArgumentException /// if the test result is false. /// @@ -350,7 +299,7 @@ namespace Spring.Util { if (!expression) { - throw new ArgumentException(message); + ThrowArgumentException(message); } } @@ -378,29 +327,38 @@ namespace Spring.Util { if (!expression) { - throw new InvalidOperationException(message); + ThrowInvalidOperationException(message); } } - - #region Constructor (s) / Destructor - // CLOVER:OFF - - /// - /// Creates a new instance of the class. - /// - /// - ///

- /// This is a utility class, and as such exposes no public constructors. - ///

- ///
- private AssertUtils() + private static void ThrowInvalidOperationException(string message) { + throw new InvalidOperationException(message); } - // CLOVER:ON - - #endregion + private static void ThrowNotSupportedException(string message) + { + throw new NotSupportedException(message); + } + private static void ThrowArgumentNullException(string paramName) + { + throw new ArgumentNullException(paramName, $"Argument '{paramName}' cannot be null."); + } + + private static void ThrowArgumentNullException(string paramName, string message) + { + throw new ArgumentNullException(paramName, message); + } + + private static void ThrowArgumentException(string message) + { + throw new ArgumentException(message); + } + + private static void ThrowArgumentException(string message, string paramName) + { + throw new ArgumentException(message, paramName); + } } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Util/CollectionUtils.cs b/src/Spring/Spring.Core/Util/CollectionUtils.cs index c9b9bed3..f8c0069e 100644 --- a/src/Spring/Spring.Core/Util/CollectionUtils.cs +++ b/src/Spring/Spring.Core/Util/CollectionUtils.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Util/ConfigurationUtils.cs b/src/Spring/Spring.Core/Util/ConfigurationUtils.cs index ce3147bf..e53ee6f9 100644 --- a/src/Spring/Spring.Core/Util/ConfigurationUtils.cs +++ b/src/Spring/Spring.Core/Util/ConfigurationUtils.cs @@ -1,5 +1,3 @@ -#region License - /* * Copyright 2002-2010 the original author or authors. * @@ -16,31 +14,23 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; +using System.Collections.Concurrent; using System.Configuration; using System.Reflection; using System.Xml; -#endregion - namespace Spring.Util { /// /// Utility class for .NET configuration files management. /// /// Aleksandar Seovic - public class ConfigurationUtils + public static class ConfigurationUtils { - /// - /// Avoid BeforeFieldInit pitfall - /// - static ConfigurationUtils() - { } - + private static readonly ConcurrentDictionary cachedSections = + new ConcurrentDictionary(); + /// /// Parses the configuration section. /// @@ -58,6 +48,11 @@ namespace Spring.Util /// Name of the configuration section. /// Object created by a corresponding . public static object GetSection(string sectionName) + { + return cachedSections.GetOrAdd(sectionName, DoGetSection); + } + + private static object DoGetSection(string sectionName) { try { @@ -71,10 +66,15 @@ namespace Spring.Util } catch (Exception ex) { - throw CreateConfigurationException(string.Format("Error reading section {0}", sectionName), ex); + throw CreateConfigurationException($"Error reading section {sectionName}", ex); } } + internal static void ClearCache() + { + cachedSections.Clear(); + } + /// /// Refresh the configuration section. /// @@ -217,7 +217,7 @@ namespace Spring.Util /// Sets the current to be used by . ///
/// - /// íf implements , this method invokes + /// �f implements , this method invokes /// on the new configSystem to chain them.
/// Note, that this method requires reflection on internals of ///
@@ -280,16 +280,5 @@ namespace Spring.Util object notStarted = Activator.CreateInstance(initStateRef.FieldType); initStateRef.SetValue(null, notStarted); } - // private static T CreateDelegate(MethodInfo method) - // { - // return (T)(object)Delegate.CreateDelegate(typeof(T), method); - // } - // - // private delegate void SetConfigurationSystemHandler(System.Configuration.Internal.IInternalConfigSystem configSystem, bool setComplete); - // - // private static SetConfigurationSystemHandler setConfigurationSystem = - // CreateDelegate(typeof(ConfigurationManager).GetMethod("SetConfigurationSystem" - // , BindingFlags.Static | BindingFlags.NonPublic)); - } } \ No newline at end of file diff --git a/src/Spring/Spring.Core/Util/ObjectUtils.cs b/src/Spring/Spring.Core/Util/ObjectUtils.cs index bb4a13da..71df73aa 100644 --- a/src/Spring/Spring.Core/Util/ObjectUtils.cs +++ b/src/Spring/Spring.Core/Util/ObjectUtils.cs @@ -1,5 +1,3 @@ -#region License - /* * Copyright 2002-2005 the original author or authors. * @@ -16,10 +14,6 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Collections; using System.Globalization; @@ -32,8 +26,6 @@ using Common.Logging; using Spring.Reflection.Dynamic; -#endregion - namespace Spring.Util { /// @@ -54,23 +46,18 @@ namespace Spring.Util /// private static readonly ILog log = LogManager.GetLogger(typeof(ObjectUtils)); - #region Constants - /// /// An empty object array. /// - public static readonly object[] EmptyObjects = new object[] { }; + public static readonly object[] EmptyObjects = { }; - private static MethodInfo GetHashCodeMethodInfo = null; - - #endregion + private static readonly MethodInfo GetHashCodeMethodInfo; static ObjectUtils() { Type type = typeof(object); GetHashCodeMethodInfo = type.GetMethod("GetHashCode"); } - #region Constructor (s) / Destructor // CLOVER:OFF @@ -88,10 +75,6 @@ namespace Spring.Util // CLOVER:ON - #endregion - - #region Methods - /// /// Instantiates the type using the assembly specified to load the type. /// @@ -145,7 +128,7 @@ namespace Spring.Util AssertUtils.ArgumentNotNull(type, "type"); ConstructorInfo constructor = GetZeroArgConstructorInfo(type); - return ObjectUtils.InstantiateType(constructor, ObjectUtils.EmptyObjects); + return InstantiateType(constructor, EmptyObjects); } /// @@ -336,17 +319,21 @@ namespace Spring.Util } } #endif + if (type.IsInstanceOfType(obj)) + { + return true; + } - return (type.IsInstanceOfType(obj) || - (type.Equals(typeof(bool)) && obj is Boolean) || - (type.Equals(typeof(byte)) && obj is Byte) || - (type.Equals(typeof(char)) && obj is Char) || - (type.Equals(typeof(sbyte)) && obj is SByte) || - (type.Equals(typeof(int)) && obj is Int32) || - (type.Equals(typeof(short)) && obj is Int16) || - (type.Equals(typeof(long)) && obj is Int64) || - (type.Equals(typeof(float)) && obj is Single) || - (type.Equals(typeof(double)) && obj is Double)); + return type.IsPrimitive && + type == typeof(bool) && obj is bool || + type == typeof(byte) && obj is byte || + type == typeof(char) && obj is char || + type == typeof(sbyte) && obj is sbyte || + type == typeof(int) && obj is int || + type == typeof(short) && obj is short || + type == typeof(long) && obj is long || + type == typeof(float) && obj is float || + type == typeof(double) && obj is double; } /// @@ -444,7 +431,7 @@ namespace Spring.Util /// public static object EnumerateFirstElement(IEnumerator enumerator) { - return ObjectUtils.EnumerateElementAtIndex(enumerator, 0); + return EnumerateElementAtIndex(enumerator, 0); } /// @@ -466,7 +453,7 @@ namespace Spring.Util public static object EnumerateFirstElement(IEnumerable enumerable) { AssertUtils.ArgumentNotNull(enumerable, "enumerable"); - return ObjectUtils.EnumerateElementAtIndex(enumerable.GetEnumerator(), 0); + return EnumerateElementAtIndex(enumerable.GetEnumerator(), 0); } /// @@ -538,11 +525,9 @@ namespace Spring.Util public static object EnumerateElementAtIndex(IEnumerable enumerable, int index) { AssertUtils.ArgumentNotNull(enumerable, "enumerable"); - return ObjectUtils.EnumerateElementAtIndex(enumerable.GetEnumerator(), index); + return EnumerateElementAtIndex(enumerable.GetEnumerator(), index); } - #endregion - /// /// Gets the qualified name of the given method, consisting of /// fully qualified interface/class name + "." method name. @@ -562,7 +547,7 @@ namespace Spring.Util /// The object's identity as String representation, /// or an empty String if the object was null /// - public static object IdentityToString(object obj) + public static string IdentityToString(object obj) { if (obj == null) { diff --git a/src/Spring/Spring.Core/Util/StringUtils.cs b/src/Spring/Spring.Core/Util/StringUtils.cs index 645d8407..2caffa53 100644 --- a/src/Spring/Spring.Core/Util/StringUtils.cs +++ b/src/Spring/Spring.Core/Util/StringUtils.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +14,12 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Collections.Generic; using System.Globalization; +using System.Runtime.CompilerServices; using System.Text; -#endregion - namespace Spring.Util { /// @@ -44,12 +37,14 @@ namespace Spring.Util /// Mark Pollack (.NET) /// Rick Evans (.NET) /// Erich Eichinger (.NET) - public sealed class StringUtils + public static class StringUtils { /// /// An empty array of instances. /// - public static readonly string[] EmptyStrings = new string[] { }; + public static readonly string[] EmptyStrings = { }; + + public static readonly IReadOnlyList EmptyStringsList = new List(); /// /// The string that signals the start of an Ant-style expression. @@ -61,26 +56,6 @@ namespace Spring.Util /// private const string AntExpressionSuffix = "}"; - #region Constructor (s) / Destructor - - // CLOVER:OFF - - /// - /// Creates a new instance of the class. - /// - /// - ///

- /// This is a utility class, and as such exposes no public constructors. - ///

- ///
- private StringUtils() - { - } - - // CLOVER:ON - - #endregion - /// /// Tokenize the given into a /// array. @@ -150,7 +125,7 @@ namespace Spring.Util } if (string.IsNullOrEmpty(delimiters)) { - return new string[] { s }; + return new[] { s }; } if (quoteChars == null) { @@ -390,10 +365,8 @@ namespace Spring.Util { return "null"; } - else - { - return StringUtils.CollectionToDelimitedString(source, delimiter); - } + + return CollectionToDelimitedString(source, delimiter); } /// Checks if a string has length. @@ -412,9 +385,10 @@ namespace Spring.Util /// StringUtils.HasLength("Hello") = true /// /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasLength(string target) { - return (target != null && target.Length > 0); + return !string.IsNullOrEmpty(target); } /// @@ -445,16 +419,10 @@ namespace Spring.Util /// StringUtils.HasText(" 12345 ") = true /// /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool HasText(string target) { - if (target == null) - { - return false; - } - else - { - return HasLength(target.Trim()); - } + return !string.IsNullOrWhiteSpace(target); } /// diff --git a/src/Spring/Spring.Data/Data/Core/RowMapperResultSetExtractor.cs b/src/Spring/Spring.Data/Data/Core/RowMapperResultSetExtractor.cs index 0696b37e..360ef8b1 100644 --- a/src/Spring/Spring.Data/Data/Core/RowMapperResultSetExtractor.cs +++ b/src/Spring/Spring.Data/Data/Core/RowMapperResultSetExtractor.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +14,11 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Collections; +using System.Collections.Generic; using Spring.Collections; -#endregion - namespace Spring.Data.Core { /// @@ -50,17 +43,10 @@ namespace Spring.Data.Core /// Mark Pollack (.NET) public class RowMapperResultSetExtractor : IResultSetExtractor { - #region Fields - - private IRowMapper rowMapper; + private readonly IRowMapper rowMapper; + private readonly RowMapperDelegate rowMapperDelegate; + private readonly int rowsExpected; - private RowMapperDelegate rowMapperDelegate; - - private int rowsExpected; - - #endregion - - #region Constructor (s) /// /// Initializes a new instance of the class. /// @@ -74,11 +60,7 @@ namespace Spring.Data.Core public RowMapperResultSetExtractor(IRowMapper rowMapper, int rowsExpected, IDataReaderWrapper dataReaderWrapper) { //TODO use datareaderwrapper - if (rowMapper == null) - { - throw new ArgumentNullException("rowMapper"); - } - this.rowMapper = rowMapper; + this.rowMapper = rowMapper ?? throw new ArgumentNullException(nameof(rowMapper)); this.rowsExpected = rowsExpected; } @@ -94,23 +76,15 @@ namespace Spring.Data.Core public RowMapperResultSetExtractor(RowMapperDelegate rowMapperDelegate, int rowsExpected, IDataReaderWrapper dataReaderWrapper) { //TODO use datareaderwrapper - if (rowMapperDelegate == null) - { - throw new ArgumentNullException("rowMapperDelegate"); - } - this.rowMapperDelegate = rowMapperDelegate; + this.rowMapperDelegate = rowMapperDelegate ?? throw new ArgumentNullException(nameof(rowMapperDelegate)); this.rowsExpected = rowsExpected; } - #endregion - - #region IResultSetExtractor Members - public object ExtractData(System.Data.IDataReader reader) { // Use the more efficient collection if we know how many rows to expect: // ArrayList in case of a known row count, LinkedList if unknown - IList results = (rowsExpected > 0) ? (IList) new ArrayList(rowsExpected) : new LinkedList(); + var results = new List(rowsExpected); int rowNum = 0; if (rowMapper != null) { @@ -129,7 +103,5 @@ namespace Spring.Data.Core return results; } - - #endregion } } diff --git a/src/Spring/Spring.Data/Data/Generic/NamedResultSetProcessor.cs b/src/Spring/Spring.Data/Data/Generic/NamedResultSetProcessor.cs index d2ecd1ee..42dcc004 100644 --- a/src/Spring/Spring.Data/Data/Generic/NamedResultSetProcessor.cs +++ b/src/Spring/Spring.Data/Data/Generic/NamedResultSetProcessor.cs @@ -1,7 +1,5 @@ -#region Licence - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +14,6 @@ * limitations under the License. */ -#endregion - namespace Spring.Data.Generic { /// @@ -27,18 +23,12 @@ namespace Spring.Data.Generic /// Mark Pollack (.NET) public class NamedResultSetProcessor { - #region Fields + private readonly IRowCallback rowCallback; + private readonly IRowMapper rowMapper; + private readonly IResultSetExtractor resultSetExtractor; + private readonly string name; - private IRowCallback rowCallback; - private IRowMapper rowMapper; - private IResultSetExtractor resultSetExtractor; - private string name; - - #endregion - - #region Constructor (s) - - /// + /// /// Initializes a new instance of the class with a /// IRowCallback instance /// @@ -75,11 +65,7 @@ namespace Spring.Data.Generic this.resultSetExtractor = resultSetExtractor; } - - #endregion - - #region Properties - public string Name + public string Name { get { @@ -102,9 +88,5 @@ namespace Spring.Data.Generic { get { return resultSetExtractor; } } - - #endregion - - } } diff --git a/src/Spring/Spring.Data/Data/Objects/Generic/StoredProcedure.cs b/src/Spring/Spring.Data/Data/Objects/Generic/StoredProcedure.cs index 73c63886..c194c7ca 100644 --- a/src/Spring/Spring.Data/Data/Objects/Generic/StoredProcedure.cs +++ b/src/Spring/Spring.Data/Data/Objects/Generic/StoredProcedure.cs @@ -1,7 +1,5 @@ -#region Licence - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +14,14 @@ * limitations under the License. */ -#endregion - -#region Imports - using System.Collections; +using System.Collections.Generic; using System.Data; -using Spring.Collections; using Spring.Dao; using Spring.Data.Common; using Spring.Data.Generic; using Spring.Data.Support; -#endregion - namespace Spring.Data.Objects.Generic { /// @@ -38,18 +30,12 @@ namespace Spring.Data.Objects.Generic /// Mark Pollack (.NET) public abstract class StoredProcedure : AdoOperation { - #region Fields - //A collection of NamedResultSetProcessor - private IList resultProcessors = new LinkedList(); + private List resultProcessors = new List(); private bool usingDerivedParameters = false; - - - #endregion - #region Constructor (s) - /// + /// /// Initializes a new instance of the class. /// public StoredProcedure() @@ -61,16 +47,6 @@ namespace Spring.Data.Objects.Generic { CommandType = CommandType.StoredProcedure; } - - - - #endregion - - #region Properties - - #endregion - - #region Methods public void DeriveParameters() { @@ -90,9 +66,7 @@ namespace Spring.Data.Objects.Generic usingDerivedParameters = true; } - - #region Non-generic result set processors - public void AddResultSetExtractor(string name, IResultSetExtractor resultSetExtractor) + public void AddResultSetExtractor(string name, IResultSetExtractor resultSetExtractor) { if (Compiled) { @@ -119,11 +93,7 @@ namespace Spring.Data.Objects.Generic resultProcessors.Add(new NamedResultSetProcessor(name, rowMapper)); } - #endregion - - #region Generic result set processors - - public void AddResultSetExtractor(string name, IResultSetExtractor resultSetExtractor) + public void AddResultSetExtractor(string name, IResultSetExtractor resultSetExtractor) { if (Compiled) { @@ -141,10 +111,8 @@ namespace Spring.Data.Objects.Generic } resultProcessors.Add(new NamedResultSetProcessor(name,rowMapper)); } - #endregion - #region Operations that use derived parameters - protected virtual IDictionary ExecuteScalar(params object[] inParameterValues) + protected virtual IDictionary ExecuteScalar(params object[] inParameterValues) { ValidateParameters(inParameterValues); return AdoTemplate.ExecuteScalar(NewCommandCreatorWithParamValues(inParameterValues)); @@ -157,7 +125,7 @@ namespace Spring.Data.Objects.Generic } - public System.Collections.Generic.IList QueryWithRowMapper(params object[] inParameterValues) + public IList QueryWithRowMapper(params object[] inParameterValues) { ValidateParameters(inParameterValues); if (resultProcessors.Count == 0) @@ -176,7 +144,7 @@ namespace Spring.Data.Objects.Generic throw new InvalidDataAccessApiUsageException("No row mapper is specified as first result set processor."); } IDictionary outParams = Query(inParameterValues); - return outParams[resultSetProcessor.Name] as System.Collections.Generic.IList; + return outParams[resultSetProcessor.Name] as IList; } @@ -194,11 +162,7 @@ namespace Spring.Data.Objects.Generic } - #endregion - - - #region Operations that used provided named parameters - /// + /// /// Execute the stored procedure using 'ExecuteScalar' /// /// Value of input parameters. @@ -229,9 +193,7 @@ namespace Spring.Data.Objects.Generic return AdoTemplate.QueryWithCommandCreator(NewCommandCreator(inParams), resultProcessors); } - #endregion - - protected override bool IsInputParameter(IDataParameter parameter) + protected override bool IsInputParameter(IDataParameter parameter) { if (usingDerivedParameters) { @@ -243,8 +205,5 @@ namespace Spring.Data.Objects.Generic return base.IsInputParameter(parameter); } } - - #endregion - } } diff --git a/src/Spring/Spring.Data/Data/Objects/StoredProcedure.cs b/src/Spring/Spring.Data/Data/Objects/StoredProcedure.cs index 98919c2d..792cce7d 100644 --- a/src/Spring/Spring.Data/Data/Objects/StoredProcedure.cs +++ b/src/Spring/Spring.Data/Data/Objects/StoredProcedure.cs @@ -1,7 +1,5 @@ -#region Licence - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +14,13 @@ * limitations under the License. */ -#endregion - -#region Imports - using System.Collections; +using System.Collections.Generic; using System.Data; -using Spring.Collections; using Spring.Dao; using Spring.Data.Common; using Spring.Data.Support; -#endregion - namespace Spring.Data.Objects { /// @@ -37,16 +29,10 @@ namespace Spring.Data.Objects /// Mark Pollack (.NET) public abstract class StoredProcedure : AdoOperation { - #region Fields - - //A collection of NamedResultSetProcessor - private IList resultProcessors = new LinkedList(); + //A collection of NamedResultSetProcessor + private readonly List resultProcessors = new List(); private bool usingDerivedParameters = false; - - - #endregion - #region Constructor (s) /// /// Initializes a new instance of the class. /// @@ -64,18 +50,8 @@ namespace Spring.Data.Objects { CommandType = CommandType.StoredProcedure; } - - - #endregion - - #region Properties - - #endregion - - #region Methods - - public void DeriveParameters() + public void DeriveParameters() { DeriveParameters(false); } @@ -177,8 +153,5 @@ namespace Spring.Data.Objects return base.IsInputParameter(parameter); } } - - #endregion - } } diff --git a/src/Spring/Spring.Data/Data/Support/NamedResultSetProcessor.cs b/src/Spring/Spring.Data/Data/Support/NamedResultSetProcessor.cs index 1c054a4d..de57a4fa 100644 --- a/src/Spring/Spring.Data/Data/Support/NamedResultSetProcessor.cs +++ b/src/Spring/Spring.Data/Data/Support/NamedResultSetProcessor.cs @@ -1,7 +1,5 @@ -#region Licence - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +14,6 @@ * limitations under the License. */ -#endregion - -#region Imports - - - -#endregion - namespace Spring.Data.Support { /// @@ -33,14 +23,9 @@ namespace Spring.Data.Support /// Mark Pollack (.NET) public class NamedResultSetProcessor { - #region Fields - - private object resultSetProcessor; - private string name; - - #endregion + private readonly object resultSetProcessor; + private readonly string name; - #region Constructor (s) /// /// Initializes a new instance of the class with a /// IRowCallback instance @@ -78,11 +63,7 @@ namespace Spring.Data.Support resultSetProcessor = resultSetExtractor; } - - #endregion - - #region Properties - public string Name + public string Name { get { @@ -97,9 +78,5 @@ namespace Spring.Data.Support return resultSetProcessor; } } - - #endregion - - } } diff --git a/src/Spring/Spring.Data/Transaction/Config/TxAdviceObjectDefinitionParser.cs b/src/Spring/Spring.Data/Transaction/Config/TxAdviceObjectDefinitionParser.cs index 41f38f1e..d699fbb1 100644 --- a/src/Spring/Spring.Data/Transaction/Config/TxAdviceObjectDefinitionParser.cs +++ b/src/Spring/Spring.Data/Transaction/Config/TxAdviceObjectDefinitionParser.cs @@ -20,6 +20,7 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Data; using System.Xml; using Spring.Collections; @@ -127,7 +128,8 @@ namespace Spring.Transaction.Config { attribute.ReadOnly = Boolean.Parse(GetAttributeValue(methodElement, READ_ONLY)); } - IList rollbackRules = new LinkedList(); + + var rollbackRules = new List(); if (methodElement.HasAttribute(ROLLBACK_FOR)) { string rollbackForValue = GetAttributeValue(methodElement, ROLLBACK_FOR); @@ -151,9 +153,7 @@ namespace Spring.Transaction.Config } - - - private void AddRollbackRuleAttributesTo(IList rollbackRules, string rollbackForValue) + private void AddRollbackRuleAttributesTo(List rollbackRules, string rollbackForValue) { string[] exceptionTypeNames = StringUtils.CommaDelimitedListToStringArray(rollbackForValue); foreach (string exceptionTypeName in exceptionTypeNames) @@ -162,7 +162,7 @@ namespace Spring.Transaction.Config } } - private void AddNoRollbackRuleAttributesTo(IList rollbackRules, string noRollbackForValue) + private void AddNoRollbackRuleAttributesTo(List rollbackRules, string noRollbackForValue) { string[] exceptionTypeNames = StringUtils.CommaDelimitedListToStringArray(noRollbackForValue); foreach (string exceptionTypeName in exceptionTypeNames) diff --git a/src/Spring/Spring.Data/Transaction/Interceptor/AbstractFallbackTransactionAttributeSource.cs b/src/Spring/Spring.Data/Transaction/Interceptor/AbstractFallbackTransactionAttributeSource.cs index a31a922f..3bbdcc8d 100644 --- a/src/Spring/Spring.Data/Transaction/Interceptor/AbstractFallbackTransactionAttributeSource.cs +++ b/src/Spring/Spring.Data/Transaction/Interceptor/AbstractFallbackTransactionAttributeSource.cs @@ -1,5 +1,3 @@ -#region License - /* * Copyright 2002-2010 the original author or authors. * @@ -16,10 +14,9 @@ * limitations under the License. */ -#endregion - using System; using System.Collections; +using System.Collections.Generic; using System.Reflection; using Spring.Collections; @@ -93,8 +90,6 @@ namespace Spring.Transaction.Interceptor { } - #region Protected Abstract Methods - /// /// Subclasses should implement this to return all attributes for this method. /// May return null. @@ -118,10 +113,6 @@ namespace Spring.Transaction.Interceptor /// protected abstract Attribute[] FindAllAttributes(Type targetType); - #endregion - - #region ITransactionAttributeSource Members - /// /// Return the transaction attribute for this method invocation. /// @@ -134,7 +125,7 @@ namespace Spring.Transaction.Interceptor /// for this method, or null if the method is non-transactional public ITransactionAttribute ReturnTransactionAttribute(MethodInfo method, Type targetType) { - object cacheKey = getCacheKey(method, targetType); + object cacheKey = GetCacheKey(method, targetType); lock (_transactionAttibuteCache) { @@ -152,7 +143,7 @@ namespace Spring.Transaction.Interceptor } else { - ITransactionAttribute transactionAttribute = computeTransactionAttribute(method, targetType); + ITransactionAttribute transactionAttribute = ComputeTransactionAttribute(method, targetType); if (null == transactionAttribute) { _transactionAttibuteCache.Add(cacheKey, NULL_TX_ATTIBUTE); @@ -166,8 +157,6 @@ namespace Spring.Transaction.Interceptor } } - #endregion - /// /// Return the transaction attribute, given this set of attributes /// attached to a method or class. Return null if it's not transactional. @@ -205,14 +194,12 @@ namespace Spring.Transaction.Interceptor } } - RuleBasedTransactionAttribute ruleBasedTransactionAttribute = transactionAttribute as RuleBasedTransactionAttribute; - if (null != ruleBasedTransactionAttribute) + if (transactionAttribute is RuleBasedTransactionAttribute ruleBasedTransactionAttribute) { - IList rollbackRules = new LinkedList(); + var rollbackRules = new List(); foreach (Attribute currentAttribute in attributes) { - RollbackRuleAttribute rollbackRuleAttribute = currentAttribute as RollbackRuleAttribute; - if (null != rollbackRuleAttribute) + if (currentAttribute is RollbackRuleAttribute rollbackRuleAttribute) { rollbackRules.Add(rollbackRuleAttribute); } @@ -223,14 +210,12 @@ namespace Spring.Transaction.Interceptor return transactionAttribute; } - #region Private Methods - - private object getCacheKey(MethodBase method, Type targetType) + private static object GetCacheKey(MethodBase method, Type targetType) { return string.Intern(targetType.AssemblyQualifiedName + "." + method); } - private ITransactionAttribute computeTransactionAttribute(MethodInfo method, Type targetType) + private ITransactionAttribute ComputeTransactionAttribute(MethodInfo method, Type targetType) { MethodInfo specificMethod; if (targetType == null) @@ -238,11 +223,11 @@ namespace Spring.Transaction.Interceptor specificMethod = method; } else - { + { ParameterInfo[] parameters = method.GetParameters(); ComposedCriteria searchCriteria = new ComposedCriteria(); - searchCriteria.Add(new MethodNameMatchCriteria(method.Name)); + searchCriteria.Add(new MethodNameMatchCriteria(method.Name)); searchCriteria.Add(new MethodParametersCountCriteria(parameters.Length)); searchCriteria.Add(new MethodGenericArgumentsCountCriteria(method.GetGenericArguments().Length)); searchCriteria.Add(new MethodParametersCriteria(ReflectionUtils.GetParameterTypes(parameters))); @@ -263,19 +248,19 @@ namespace Spring.Transaction.Interceptor } } - ITransactionAttribute transactionAttribute = getTransactionAttribute(specificMethod); + ITransactionAttribute transactionAttribute = GetTransactionAttribute(specificMethod); if (null != transactionAttribute) { return transactionAttribute; } else if (specificMethod != method) { - transactionAttribute = getTransactionAttribute(method); + transactionAttribute = GetTransactionAttribute(method); } return null; } - private ITransactionAttribute getTransactionAttribute(MethodInfo methodInfo) + private ITransactionAttribute GetTransactionAttribute(MethodInfo methodInfo) { ITransactionAttribute transactionAttribute = FindTransactionAttribute(FindAllAttributes(methodInfo)); @@ -290,7 +275,5 @@ namespace Spring.Transaction.Interceptor } return null; } - - #endregion } } \ No newline at end of file diff --git a/src/Spring/Spring.Data/Transaction/Interceptor/AttributesTransactionAttributeSource.cs b/src/Spring/Spring.Data/Transaction/Interceptor/AttributesTransactionAttributeSource.cs index b5b0bb85..94d516fe 100644 --- a/src/Spring/Spring.Data/Transaction/Interceptor/AttributesTransactionAttributeSource.cs +++ b/src/Spring/Spring.Data/Transaction/Interceptor/AttributesTransactionAttributeSource.cs @@ -20,6 +20,7 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Reflection; namespace Spring.Transaction.Interceptor @@ -93,7 +94,7 @@ namespace Spring.Transaction.Interceptor Type[] rbf = ta.RollbackFor; - IList rollBackRules = new ArrayList(); + var rollBackRules = new List(); if (rbf != null) { diff --git a/src/Spring/Spring.Data/Transaction/Interceptor/RuleBasedTransactionAttribute.cs b/src/Spring/Spring.Data/Transaction/Interceptor/RuleBasedTransactionAttribute.cs index 1cf265a0..2ee4afee 100644 --- a/src/Spring/Spring.Data/Transaction/Interceptor/RuleBasedTransactionAttribute.cs +++ b/src/Spring/Spring.Data/Transaction/Interceptor/RuleBasedTransactionAttribute.cs @@ -20,6 +20,7 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Text; using Spring.Collections; @@ -44,7 +45,7 @@ namespace Spring.Transaction.Interceptor /// Griffin Caprio (.NET) public class RuleBasedTransactionAttribute : DefaultTransactionAttribute { - private IList _rollbackRules; + private IList _rollbackRules; /// /// Creates a new instance of the @@ -58,7 +59,8 @@ namespace Spring.Transaction.Interceptor /// The rollback rules list for this transaction attribute. /// public RuleBasedTransactionAttribute( - TransactionPropagation transactionPropagation, IList ruleList ) + TransactionPropagation transactionPropagation, + IList ruleList ) : base(transactionPropagation) { _rollbackRules = ruleList; @@ -71,15 +73,15 @@ namespace Spring.Transaction.Interceptor /// public RuleBasedTransactionAttribute( ) { - _rollbackRules = new ArrayList(); + _rollbackRules = new List(); } /// /// Sets the rollback rules list for this transaction attribute. /// - public IList RollbackRules + public IList RollbackRules { - set { _rollbackRules = value; } + set => _rollbackRules = value; } /// diff --git a/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/CachedSession.cs b/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/CachedSession.cs index 07758049..145931d8 100644 --- a/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/CachedSession.cs +++ b/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/CachedSession.cs @@ -1,5 +1,3 @@ -#region License - /* * Copyright 2002-2010 the original author or authors. * @@ -16,8 +14,6 @@ * limitations under the License. */ -#endregion - using System; using System.Collections; using System.Collections.Generic; @@ -40,22 +36,18 @@ namespace Spring.Messaging.Nms.Connections /// Mark Pollack public class CachedSession : IDecoratorSession { - #region Logging Definition + private static readonly ILog Log = LogManager.GetLogger(typeof(CachedSession)); - private static readonly ILog LOG = LogManager.GetLogger(typeof(CachedSession)); - - #endregion - - private ISession target; - private LinkedList sessionList; - private int sessionCacheSize; - private IDictionary cachedProducers = new Hashtable(); - private IDictionary cachedConsumers = new Hashtable(); + private readonly ISession target; + private readonly List sessionList; + private readonly int sessionCacheSize; + private readonly Dictionary cachedProducers = new Dictionary(); + private readonly Dictionary cachedConsumers = new Dictionary(); private IMessageProducer cachedUnspecifiedDestinationMessageProducer; - private bool shouldCacheProducers; - private bool shouldCacheConsumers; + private readonly bool shouldCacheProducers; + private readonly bool shouldCacheConsumers; private bool transactionOpen = false; - private CachingConnectionFactory ccf; + private readonly CachingConnectionFactory ccf; /// /// Initializes a new instance of the class. @@ -63,7 +55,10 @@ namespace Spring.Messaging.Nms.Connections /// The target session. /// The session list. /// The CachingConnectionFactory. - public CachedSession(ISession targetSession, LinkedList sessionList, CachingConnectionFactory ccf) + public CachedSession( + ISession targetSession, + List sessionList, + CachingConnectionFactory ccf) { target = targetSession; this.sessionList = sessionList; @@ -78,10 +73,7 @@ namespace Spring.Messaging.Nms.Connections /// Gets the target, for testing purposes. /// /// The target. - public ISession TargetSession - { - get { return target; } - } + public ISession TargetSession => target; /// /// Creates the producer, potentially returning a cached instance. @@ -93,29 +85,22 @@ namespace Spring.Messaging.Nms.Connections { if (cachedUnspecifiedDestinationMessageProducer != null) { - #region Logging - - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.Debug("Found cached MessageProducer for unspecified destination"); + Log.Debug("Found cached MessageProducer for unspecified destination"); } - - #endregion } else { - #region Logging - - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.Debug("Creating cached MessageProducer for unspecified destination"); + Log.Debug("Creating cached MessageProducer for unspecified destination"); } - #endregion cachedUnspecifiedDestinationMessageProducer = target.CreateProducer(); } - this.transactionOpen = true; + transactionOpen = true; return new CachedMessageProducer(cachedUnspecifiedDestinationMessageProducer); } else @@ -135,33 +120,26 @@ namespace Spring.Messaging.Nms.Connections if (shouldCacheProducers) { - IMessageProducer producer = (IMessageProducer)cachedProducers[destination]; - if (producer != null) + if (cachedProducers.TryGetValue(destination, out var producer)) { - #region Logging - - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.Debug("Found cached MessageProducer for destination [" + destination + "]"); + Log.Debug("Found cached MessageProducer for destination [" + destination + "]"); } - - #endregion } else { producer = target.CreateProducer(destination); - #region Logging - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.Debug("Creating cached MessageProducer for destination [" + destination + "]"); + Log.Debug("Creating cached MessageProducer for destination [" + destination + "]"); } - #endregion - cachedProducers.Add(destination, producer); + cachedProducers[destination] = producer; } - this.transactionOpen = true; + transactionOpen = true; return new CachedMessageProducer(producer); } else @@ -197,20 +175,20 @@ namespace Spring.Messaging.Nms.Connections private void LogicalClose() { // Preserve rollback-on-close semantics. - if (this.transactionOpen && this.target.Transacted) + if (transactionOpen && target.Transacted) { - this.transactionOpen = false; - this.target.Rollback(); + transactionOpen = false; + target.Rollback(); } // Physically close durable subscribers at time of Session close call. - List toRemove = new List(); - foreach (DictionaryEntry dictionaryEntry in cachedConsumers) + var toRemove = new List(); + foreach (var dictionaryEntry in cachedConsumers) { - ConsumerCacheKey key = (ConsumerCacheKey) dictionaryEntry.Key; + ConsumerCacheKey key = dictionaryEntry.Key; if (key.Subscription != null) { - ((IMessageConsumer) dictionaryEntry.Value).Close(); + dictionaryEntry.Value.Close(); toRemove.Add(key); } } @@ -222,36 +200,32 @@ namespace Spring.Messaging.Nms.Connections // Allow for multiple close calls... if (!sessionList.Contains(this)) { - #region Logging - - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.Debug("Returning cached Session: " + target); + Log.Debug("Returning cached Session: " + target); } - #endregion - sessionList.Add(this); //add to end of linked list. } } private void PhysicalClose() { - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.Debug("Closing cached Session: " + this.target); + Log.Debug("Closing cached Session: " + target); } // Explicitly close all MessageProducers and MessageConsumers that // this Session happens to cache... try { - foreach (DictionaryEntry entry in cachedProducers) + foreach (var entry in cachedProducers) { - ((IMessageProducer)entry.Value).Close(); + entry.Value.Close(); } - foreach (DictionaryEntry entry in cachedConsumers) + foreach (var entry in cachedConsumers) { - ((IMessageConsumer)entry.Value).Close(); + entry.Value.Close(); } } finally @@ -305,7 +279,7 @@ namespace Spring.Messaging.Nms.Connections /// A message consumer public IMessageConsumer CreateDurableConsumer(ITopic destination, string subscription, string selector, bool noLocal) { - this.transactionOpen = true; + transactionOpen = true; if (shouldCacheConsumers) { return GetCachedConsumer(destination, selector, noLocal, subscription); @@ -340,7 +314,7 @@ namespace Spring.Messaging.Nms.Connections /// protected IMessageConsumer CreateConsumer(IDestination destination, string selector, bool noLocal, string durableSubscriptionName) { - this.transactionOpen = true; + transactionOpen = true; if (shouldCacheConsumers) { return GetCachedConsumer(destination, selector, noLocal, durableSubscriptionName); @@ -353,38 +327,35 @@ namespace Spring.Messaging.Nms.Connections private IMessageConsumer GetCachedConsumer(IDestination destination, string selector, bool noLocal, string durableSubscriptionName) { - object cacheKey = new ConsumerCacheKey(destination, selector, noLocal, durableSubscriptionName); - IMessageConsumer consumer = (IMessageConsumer)cachedConsumers[cacheKey]; - if (consumer != null) + var cacheKey = new ConsumerCacheKey(destination, selector, noLocal, durableSubscriptionName); + if (cachedConsumers.TryGetValue(cacheKey, out var consumer)) { - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.Debug("Found cached NMS MessageConsumer for destination [" + destination + "]: " + consumer); + Log.Debug("Found cached NMS MessageConsumer for destination [" + destination + "]: " + consumer); } } else { - if (destination is ITopic) + if (destination is ITopic topic) { consumer = (durableSubscriptionName != null - ? target.CreateDurableConsumer((ITopic)destination, durableSubscriptionName, selector, noLocal) - : target.CreateConsumer(destination, selector, noLocal)); + ? target.CreateDurableConsumer(topic, durableSubscriptionName, selector, noLocal) + : target.CreateConsumer(topic, selector, noLocal)); } else { consumer = target.CreateConsumer(destination, selector); } - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.Debug("Creating cached NMS MessageConsumer for destination [" + destination + "]: " + consumer); + Log.Debug("Creating cached NMS MessageConsumer for destination [" + destination + "]: " + consumer); } cachedConsumers[cacheKey] = consumer; } return new CachedMessageConsumer(consumer); } - #region Pass through implementations - /// /// Gets the queue. /// @@ -392,7 +363,7 @@ namespace Spring.Messaging.Nms.Connections /// public IQueue GetQueue(string name) { - this.transactionOpen = true; + transactionOpen = true; return target.GetQueue(name); } @@ -403,7 +374,7 @@ namespace Spring.Messaging.Nms.Connections /// public ITopic GetTopic(string name) { - this.transactionOpen = true; + transactionOpen = true; return target.GetTopic(name); } @@ -413,7 +384,7 @@ namespace Spring.Messaging.Nms.Connections /// public ITemporaryQueue CreateTemporaryQueue() { - this.transactionOpen = true; + transactionOpen = true; return target.CreateTemporaryQueue(); } @@ -423,7 +394,7 @@ namespace Spring.Messaging.Nms.Connections /// public ITemporaryTopic CreateTemporaryTopic() { - this.transactionOpen = true; + transactionOpen = true; return target.CreateTemporaryTopic(); } @@ -433,7 +404,7 @@ namespace Spring.Messaging.Nms.Connections /// The destination. public void DeleteDestination(IDestination destination) { - this.transactionOpen = true; + transactionOpen = true; target.DeleteDestination(destination); } @@ -443,7 +414,7 @@ namespace Spring.Messaging.Nms.Connections /// public IMessage CreateMessage() { - this.transactionOpen = true; + transactionOpen = true; return target.CreateMessage(); } @@ -453,7 +424,7 @@ namespace Spring.Messaging.Nms.Connections /// public ITextMessage CreateTextMessage() { - this.transactionOpen = true; + transactionOpen = true; return target.CreateTextMessage(); } @@ -464,7 +435,7 @@ namespace Spring.Messaging.Nms.Connections /// public ITextMessage CreateTextMessage(string text) { - this.transactionOpen = true; + transactionOpen = true; return target.CreateTextMessage(text); } @@ -474,7 +445,7 @@ namespace Spring.Messaging.Nms.Connections /// public IMapMessage CreateMapMessage() { - this.transactionOpen = true; + transactionOpen = true; return target.CreateMapMessage(); } @@ -485,7 +456,7 @@ namespace Spring.Messaging.Nms.Connections /// public IObjectMessage CreateObjectMessage(object body) { - this.transactionOpen = true; + transactionOpen = true; return target.CreateObjectMessage(body); } @@ -495,7 +466,7 @@ namespace Spring.Messaging.Nms.Connections /// public IBytesMessage CreateBytesMessage() { - this.transactionOpen = true; + transactionOpen = true; return target.CreateBytesMessage(); } @@ -506,7 +477,7 @@ namespace Spring.Messaging.Nms.Connections /// public IBytesMessage CreateBytesMessage(byte[] body) { - this.transactionOpen = true; + transactionOpen = true; return target.CreateBytesMessage(body); } @@ -516,7 +487,7 @@ namespace Spring.Messaging.Nms.Connections /// public IStreamMessage CreateStreamMessage() { - this.transactionOpen = true; + transactionOpen = true; return target.CreateStreamMessage(); } @@ -525,7 +496,7 @@ namespace Spring.Messaging.Nms.Connections /// public void Commit() { - this.transactionOpen = false; + transactionOpen = false; target.Commit(); } @@ -537,7 +508,7 @@ namespace Spring.Messaging.Nms.Connections /// public void Recover() { - this.transactionOpen = true; + transactionOpen = true; target.Recover(); } @@ -546,7 +517,7 @@ namespace Spring.Messaging.Nms.Connections /// public void Rollback() { - this.transactionOpen = false; + transactionOpen = false; target.Rollback(); } @@ -558,8 +529,8 @@ namespace Spring.Messaging.Nms.Connections /// public ConsumerTransformerDelegate ConsumerTransformer { - get { return target.ConsumerTransformer; } - set { target.ConsumerTransformer = value; } + get => target.ConsumerTransformer; + set => target.ConsumerTransformer = value; } /// @@ -570,8 +541,8 @@ namespace Spring.Messaging.Nms.Connections /// public ProducerTransformerDelegate ProducerTransformer { - get { return target.ProducerTransformer; } - set { target.ProducerTransformer = value; } + get => target.ProducerTransformer; + set => target.ProducerTransformer = value; } /// /// Gets or sets the request timeout. @@ -579,8 +550,8 @@ namespace Spring.Messaging.Nms.Connections /// The request timeout. public TimeSpan RequestTimeout { - get { return target.RequestTimeout; } - set { target.RequestTimeout = value; } + get => target.RequestTimeout; + set => target.RequestTimeout = value; } /// @@ -591,7 +562,7 @@ namespace Spring.Messaging.Nms.Connections { get { - this.transactionOpen = true; + transactionOpen = true; return target.Transacted; } } @@ -604,7 +575,7 @@ namespace Spring.Messaging.Nms.Connections { get { - this.transactionOpen = true; + transactionOpen = true; return target.AcknowledgementMode; } } @@ -614,8 +585,8 @@ namespace Spring.Messaging.Nms.Connections /// public event SessionTxEventDelegate TransactionStartedListener { - add { target.TransactionStartedListener += value; } - remove { target.TransactionStartedListener -= value; } + add => target.TransactionStartedListener += value; + remove => target.TransactionStartedListener -= value; } /// @@ -623,8 +594,8 @@ namespace Spring.Messaging.Nms.Connections /// public event SessionTxEventDelegate TransactionCommittedListener { - add { target.TransactionCommittedListener += value; } - remove { target.TransactionCommittedListener -= value; } + add => target.TransactionCommittedListener += value; + remove => target.TransactionCommittedListener -= value; } /// @@ -632,8 +603,8 @@ namespace Spring.Messaging.Nms.Connections /// public event SessionTxEventDelegate TransactionRolledBackListener { - add { target.TransactionRolledBackListener += value; } - remove { target.TransactionRolledBackListener -= value; } + add => target.TransactionRolledBackListener += value; + remove => target.TransactionRolledBackListener -= value; } /// @@ -641,7 +612,7 @@ namespace Spring.Messaging.Nms.Connections /// public void Dispose() { - this.transactionOpen = true; + transactionOpen = true; target.Dispose(); } @@ -653,7 +624,7 @@ namespace Spring.Messaging.Nms.Connections /// The Queue browser public IQueueBrowser CreateBrowser(IQueue queue, string selector) { - this.transactionOpen = true; + transactionOpen = true; return target.CreateBrowser(queue, selector); } @@ -664,10 +635,9 @@ namespace Spring.Messaging.Nms.Connections /// The Queue browser public IQueueBrowser CreateBrowser(IQueue queue) { - this.transactionOpen = true; + transactionOpen = true; return target.CreateBrowser(queue); } - #endregion /// /// Returns a that represents the current . @@ -677,16 +647,16 @@ namespace Spring.Messaging.Nms.Connections /// public override string ToString() { - return "Cached NMS Session: " + this.target; + return "Cached NMS Session: " + target; } } internal class ConsumerCacheKey { - private IDestination destination; - private string selector; - private bool noLocal; - private string subscription; + private readonly IDestination destination; + private readonly string selector; + private readonly bool noLocal; + private readonly string subscription; public ConsumerCacheKey(IDestination destination, string selector, bool noLocal, string subscription) { @@ -696,10 +666,7 @@ namespace Spring.Messaging.Nms.Connections this.subscription = subscription; } - public string Subscription - { - get { return subscription; } - } + public string Subscription => subscription; protected bool Equals(ConsumerCacheKey consumerCacheKey) { diff --git a/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/CachingConnectionFactory.cs b/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/CachingConnectionFactory.cs index d7316cd3..68737338 100644 --- a/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/CachingConnectionFactory.cs +++ b/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/CachingConnectionFactory.cs @@ -1,5 +1,3 @@ -#region License - /* * Copyright 2002-2010 the original author or authors. * @@ -16,10 +14,9 @@ * limitations under the License. */ -#endregion - using System; using System.Collections; +using System.Collections.Generic; using Apache.NMS; using Common.Logging; using Spring.Collections; @@ -58,22 +55,14 @@ namespace Spring.Messaging.Nms.Connections /// Mark Pollack (.NET) public class CachingConnectionFactory : SingleConnectionFactory { - #region Logging Definition - - private static readonly ILog LOG = LogManager.GetLogger(typeof(CachingConnectionFactory)); - - #endregion + private static readonly ILog Log = LogManager.GetLogger(typeof(CachingConnectionFactory)); private int sessionCacheSize = 1; - private bool cacheProducers = true; - - private bool cacheConsumers = true; - private volatile bool active = true; - private IDictionary cachedSessions = new Hashtable(); - + private readonly Dictionary> cachedSessions = + new Dictionary>(); /// /// Initializes a new instance of the class. @@ -94,7 +83,6 @@ namespace Spring.Messaging.Nms.Connections ReconnectOnException = true; } - /// /// Gets or sets the size of the session cache. /// @@ -113,7 +101,7 @@ namespace Spring.Messaging.Nms.Connections /// The size of the session cache. public int SessionCacheSize { - get { return sessionCacheSize; } + get => sessionCacheSize; set { AssertUtils.IsTrue(value >= 1, "Session cache size must be 1 or higher"); @@ -121,7 +109,6 @@ namespace Spring.Messaging.Nms.Connections } } - /// /// Gets or sets a value indicating whether to cache MessageProducers per /// Session instance. (more specifically: one MessageProducer per Destination @@ -133,12 +120,7 @@ namespace Spring.Messaging.Nms.Connections /// /// /// true if should cache message producers; otherwise, false. - public bool CacheProducers - { - get { return cacheProducers; } - set { cacheProducers = value; } - } - + public bool CacheProducers { get; set; } = true; /// /// Gets or sets a value indicating whether o cache JMS MessageConsumers per @@ -154,11 +136,7 @@ namespace Spring.Messaging.Nms.Connections /// /// /// true to cache consumers per session instance; otherwise, false. - public bool CacheConsumers - { - get { return cacheConsumers; } - set { cacheConsumers = value; } - } + public bool CacheConsumers { get; set; } = true; /// /// Gets or sets a value indicating whether this instance is active. @@ -166,8 +144,8 @@ namespace Spring.Messaging.Nms.Connections /// true if this instance is active; otherwise, false. public bool IsActive { - get { return active; } - set { active = value; } + get => active; + set => active = value; } /// @@ -178,9 +156,9 @@ namespace Spring.Messaging.Nms.Connections this.active = false; lock (cachedSessions) { - foreach (DictionaryEntry dictionaryEntry in cachedSessions) + foreach (var pair in cachedSessions) { - LinkedList sessionList = (LinkedList) dictionaryEntry.Value; + var sessionList = pair.Value; lock (sessionList) { foreach (ISession session in sessionList) @@ -191,13 +169,15 @@ namespace Spring.Messaging.Nms.Connections } catch (Exception ex) { - LOG.Trace("Could not close cached NMS Session", ex); + Log.Trace("Could not close cached NMS Session", ex); } } } } - cachedSessions.Clear(); + + cachedSessions.Clear(); } + this.active = true; // Now proceed with actual closing of the shared Connection... base.ResetConnection(); @@ -212,14 +192,13 @@ namespace Spring.Messaging.Nms.Connections /// public override ISession GetSession(IConnection con, AcknowledgementMode mode) { - LinkedList sessionList; + List sessionList; lock (cachedSessions) { - sessionList = (LinkedList) cachedSessions[mode]; - if (sessionList == null) + if (!cachedSessions.TryGetValue(mode, out sessionList)) { - sessionList = new LinkedList(); - cachedSessions.Add(mode, sessionList); + sessionList = new List(); + cachedSessions[mode] = sessionList; } } @@ -228,42 +207,44 @@ namespace Spring.Messaging.Nms.Connections { if (sessionList.Count > 0) { - session = (ISession) sessionList[0]; + session = sessionList[0]; sessionList.RemoveAt(0); } } + if (session != null) { - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.Debug("Found cached Session for mode " + mode + ": " - + (session is IDecoratorSession ? ((IDecoratorSession) session).TargetSession : session)); + Log.Debug("Found cached Session for mode " + mode + ": " + + (session is IDecoratorSession decoratorSession ? decoratorSession.TargetSession : session)); } - } else + } + else { - ISession targetSession = con.CreateSession(mode); - if (LOG.IsDebugEnabled) + ISession targetSession = con.CreateSession(mode); + if (Log.IsDebugEnabled) { - LOG.Debug("Creating cached Session for mode " + mode + ": " + targetSession); + Log.Debug("Creating cached Session for mode " + mode + ": " + targetSession); } + session = GetCachedSessionWrapper(targetSession, sessionList); } + return session; } /// /// Wraps the given Session so that it delegates every method call to the target session but /// adapts close calls. This is useful for allowing application code to - /// handle a special framework Session just like an ordinary Session. + /// handle a special framework Session just like an ordinary Session. /// /// The original Session to wrap. /// The List of cached Sessions that the given Session belongs to. /// The wrapped Session - protected virtual ISession GetCachedSessionWrapper(ISession targetSession, LinkedList sessionList) + protected virtual ISession GetCachedSessionWrapper(ISession targetSession, List sessionList) { return new CachedSession(targetSession, sessionList, this); } } - - } \ No newline at end of file diff --git a/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/NmsResourceHolder.cs b/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/NmsResourceHolder.cs index ea78fdf1..d7389ea2 100644 --- a/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/NmsResourceHolder.cs +++ b/src/Spring/Spring.Messaging.Nms/Messaging/Nms/Connections/NmsResourceHolder.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +14,9 @@ * limitations under the License. */ -#endregion - using System; using System.Collections; +using System.Collections.Generic; using Common.Logging; using Spring.Collections; using Spring.Transaction.Support; @@ -39,28 +36,13 @@ namespace Spring.Messaging.Nms.Connections /// Mark Pollack (.NET) public class NmsResourceHolder : ResourceHolderSupport { - #region Logging - private static readonly ILog logger = LogManager.GetLogger(typeof(NmsResourceHolder)); - #endregion - - #region Fields - - private IConnectionFactory connectionFactory; - - private bool frozen = false; - - private IList connections = new LinkedList(); - - private IList sessions = new LinkedList(); - - private IDictionary sessionsPerIConnection = new Hashtable(); - - #endregion - - - #region Constructor (s) + private readonly IConnectionFactory connectionFactory; + private readonly bool frozen = false; + private readonly List connections = new List(); + private readonly List sessions = new List(); + private readonly Dictionary> sessionsPerIConnection = new Dictionary>(); /// Create a new MessageResourceHolder that is open for resources to be added. public NmsResourceHolder() @@ -100,7 +82,7 @@ namespace Spring.Messaging.Nms.Connections { AddConnection(connection); AddSession(session, connection); - this.frozen = true; + frozen = true; } /// @@ -114,11 +96,8 @@ namespace Spring.Messaging.Nms.Connections this.connectionFactory = connectionFactory; AddConnection(connection); AddSession(session, connection); - this.frozen = true; + frozen = true; } - #endregion - - #region Properties /// /// Gets a value indicating whether this is frozen, namely that @@ -126,17 +105,7 @@ namespace Spring.Messaging.Nms.Connections /// a Session, the holder will be set to the frozen state. /// /// true if frozen; otherwise, false. - virtual public bool Frozen - { - get - { - return frozen; - } - - } - #endregion - - #region Methods + public virtual bool Frozen => frozen; /// /// Adds the connection to the list of resources managed by this holder. @@ -175,10 +144,9 @@ namespace Spring.Messaging.Nms.Connections sessions.Add(session); if (connection != null) { - IList sessionsList = (IList)sessionsPerIConnection[connection]; - if (sessionsList == null) + if (!sessionsPerIConnection.TryGetValue(connection, out var sessionsList)) { - sessionsList = new LinkedList(); + sessionsList = new List(); sessionsPerIConnection[connection] = sessionsList; } sessionsList.Add(session); @@ -192,7 +160,7 @@ namespace Spring.Messaging.Nms.Connections /// A Connection, or null if no managed connection. public virtual IConnection GetConnection() { - return (!(this.connections.Count == 0) ? (IConnection)this.connections[0] : null); + return (connections.Count != 0 ? connections[0] : null); } /// @@ -204,7 +172,7 @@ namespace Spring.Messaging.Nms.Connections /// The connection, or null if not found. public virtual IConnection GetConnection(Type connectionType) { - return (IConnection)CollectionUtils.FindValueOfType(this.connections, connectionType); + return (IConnection)CollectionUtils.FindValueOfType(connections, connectionType); } /// @@ -213,7 +181,7 @@ namespace Spring.Messaging.Nms.Connections /// The session or null if not available. public virtual ISession GetSession() { - return (!(this.sessions.Count == 0) ? (ISession)this.sessions[0] : null); + return sessions.Count != 0 ? sessions[0] : null; } /// @@ -234,12 +202,13 @@ namespace Spring.Messaging.Nms.Connections /// The sessin or null if not available. public virtual ISession GetSession(Type sessionType, IConnection connection) { - IList sessions = this.sessions; + var sessions = this.sessions; if (connection != null) { - sessions = (IList)sessionsPerIConnection[connection]; + sessionsPerIConnection.TryGetValue(connection, out sessions); } - return (ISession)CollectionUtils.FindValueOfType(sessions, sessionType); + + return (ISession) CollectionUtils.FindValueOfType(sessions, sessionType); } /// @@ -273,9 +242,9 @@ namespace Spring.Messaging.Nms.Connections { ConnectionFactoryUtils.ReleaseConnection(connection, connectionFactory, true); } - this.connections.Clear(); - this.sessions.Clear(); - this.sessionsPerIConnection.Clear(); + connections.Clear(); + sessions.Clear(); + sessionsPerIConnection.Clear(); } /// @@ -287,9 +256,7 @@ namespace Spring.Messaging.Nms.Connections /// public bool ContainsSession(ISession session) { - return this.sessions.Contains(session); + return sessions.Contains(session); } - - #endregion } } diff --git a/src/Spring/Spring.Scheduling.Quartz3/Scheduling/Quartz/SchedulerAccessor.cs b/src/Spring/Spring.Scheduling.Quartz3/Scheduling/Quartz/SchedulerAccessor.cs index b7000b86..b7a427bb 100644 --- a/src/Spring/Spring.Scheduling.Quartz3/Scheduling/Quartz/SchedulerAccessor.cs +++ b/src/Spring/Spring.Scheduling.Quartz3/Scheduling/Quartz/SchedulerAccessor.cs @@ -51,7 +51,7 @@ namespace Spring.Scheduling.Quartz private string[] jobSchedulingDataLocations; - private IList jobDetails; + private IList jobDetails; private IDictionary calendars; private IList triggers; @@ -277,7 +277,7 @@ namespace Spring.Scheduling.Quartz else { // Create empty list for easier checks when registering triggers. - jobDetails = new LinkedList(); + jobDetails = new List(); } // Register Calendars. diff --git a/src/Spring/Spring.Web/Objects/Factory/Support/RootWebObjectDefinition.cs b/src/Spring/Spring.Web/Objects/Factory/Support/RootWebObjectDefinition.cs index 421ff6ad..5408d6a4 100644 --- a/src/Spring/Spring.Web/Objects/Factory/Support/RootWebObjectDefinition.cs +++ b/src/Spring/Spring.Web/Objects/Factory/Support/RootWebObjectDefinition.cs @@ -199,10 +199,10 @@ namespace Spring.Objects.Factory.Support public override void OverrideFrom(IObjectDefinition other) { base.OverrideFrom(other); - if (other is IWebObjectDefinition) + if (other is IWebObjectDefinition definition) { // this._scope = ((IWebObjectDefinition) other).Scope; - this._pageName = ((IWebObjectDefinition) other).PageName; + this._pageName = definition.PageName; } } diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Support/RootObjectDefinitionTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Support/RootObjectDefinitionTests.cs index af3f8ef5..6f6a978d 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Support/RootObjectDefinitionTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Support/RootObjectDefinitionTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/UnsupportedObjectDefinitionImplementation.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/UnsupportedObjectDefinitionImplementation.cs index 252cf996..0f62bb4e 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/UnsupportedObjectDefinitionImplementation.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/UnsupportedObjectDefinitionImplementation.cs @@ -116,7 +116,7 @@ namespace Spring.Objects.Factory get { throw new NotImplementedException(); } } - public IList DependsOn + public IReadOnlyList DependsOn { get { throw new NotImplementedException(); } } diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlListableObjectFactoryTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlListableObjectFactoryTests.cs index 455a603a..b7a4f5c1 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlListableObjectFactoryTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlListableObjectFactoryTests.cs @@ -83,7 +83,7 @@ namespace Spring.Objects.Factory.Xml protected void SetUp() { parent = new DefaultListableObjectFactory(); - IDictionary m = new Dictionary(); + var m = new Dictionary(); m["name"] = "Albert"; parent.RegisterObjectDefinition("father", new RootObjectDefinition(typeof(TestObject), new MutablePropertyValues(m))); m = new Dictionary(); diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectCollectionTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectCollectionTests.cs index fda13730..87787773 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectCollectionTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectCollectionTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,6 @@ #endregion -#region Imports - using System; using System.Collections; using System.Collections.Generic; @@ -35,8 +33,6 @@ using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Support; using Spring.Util; -#endregion - namespace Spring.Objects.Factory.Xml { /// diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectFactoryTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectFactoryTests.cs index 3bd9142a..e338cc0c 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectFactoryTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectFactoryTests.cs @@ -1,5 +1,5 @@ /* - * Copyright © 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -963,8 +963,8 @@ namespace Spring.Objects.Factory.Xml LazyWorker lw1 = new LazyWorker(xof); LazyWorker lw2 = new LazyWorker(xof); - Thread thread1 = new Thread(new ThreadStart(lw1.DoWork)); - Thread thread2 = new Thread(new ThreadStart(lw2.DoWork)); + Thread thread1 = new Thread(lw1.DoWork); + Thread thread2 = new Thread(lw2.DoWork); thread1.Start(); Thread.Sleep(1000); @@ -1883,10 +1883,7 @@ namespace Spring.Objects.Factory.Xml objectFromContext = xof.GetObject("lazyObject"); } - public Object ObjectFromContext - { - get { return objectFromContext; } - } + public Object ObjectFromContext => objectFromContext; } public sealed class MyTestObject { @@ -1894,20 +1891,17 @@ namespace Spring.Objects.Factory.Xml public Type[] Types { - get { return _types; } - set { _types = value; } + get => _types; + set => _types = value; } public CultureInfo Culture { - get { return _culture; } - set { _culture = value; } + get => _culture; + set => _culture = value; } - public CultureInfo MyDefaultCulture - { - get { return Default; } - } + public CultureInfo MyDefaultCulture => Default; private Type[] _types; private CultureInfo _culture; @@ -1925,8 +1919,8 @@ namespace Spring.Objects.Factory.Xml { public int Num { - get { return num; } - set { num = value; } + get => num; + set => num = value; } private int num; diff --git a/test/Spring/Spring.Core.Tests/Objects/MutablePropertyValuesTests.cs b/test/Spring/Spring.Core.Tests/Objects/MutablePropertyValuesTests.cs index 8d09dc19..5ea4e73f 100644 --- a/test/Spring/Spring.Core.Tests/Objects/MutablePropertyValuesTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/MutablePropertyValuesTests.cs @@ -75,7 +75,7 @@ namespace Spring.Objects [Test] public void InstantiationWithNulls () { - MutablePropertyValues props = new MutablePropertyValues ((IDictionary) null); + MutablePropertyValues props = new MutablePropertyValues((Dictionary) null); Assert.AreEqual (0, props.PropertyValues.Count); MutablePropertyValues props2 = new MutablePropertyValues ((IPropertyValues) null); Assert.AreEqual (0, props2.PropertyValues.Count); @@ -97,7 +97,7 @@ namespace Spring.Objects MutablePropertyValues props = new MutablePropertyValues (); props.Add (new PropertyValue ("Name", "Fiona Apple")); props.Add (new PropertyValue ("Age", 24)); - props.AddAll ((IList) null); + props.AddAll((List) null); Assert.AreEqual (2, props.PropertyValues.Count); } @@ -157,7 +157,7 @@ namespace Spring.Objects [Test] public void ChangesSince () { - IDictionary map = new Dictionary(); + Dictionary map = new Dictionary(); PropertyValue propName = new PropertyValue("Name", "Fiona Apple"); map.Add (propName.Name, propName.Value); map.Add ("Age", 24); @@ -183,7 +183,7 @@ namespace Spring.Objects [Test] public void ChangesSinceWithSelf () { - IDictionary map = new Dictionary(); + Dictionary map = new Dictionary(); map.Add("Name", "Fiona Apple"); map.Add ("Age", 24); MutablePropertyValues props = new MutablePropertyValues (map); diff --git a/test/Spring/Spring.Data.Tests/Transaction/Interceptor/RuleBasedTransactionAttributeTests.cs b/test/Spring/Spring.Data.Tests/Transaction/Interceptor/RuleBasedTransactionAttributeTests.cs index 9ac6438a..06a2f45e 100644 --- a/test/Spring/Spring.Data.Tests/Transaction/Interceptor/RuleBasedTransactionAttributeTests.cs +++ b/test/Spring/Spring.Data.Tests/Transaction/Interceptor/RuleBasedTransactionAttributeTests.cs @@ -1,8 +1,7 @@ using System; -using System.Collections; +using System.Collections.Generic; using System.Data; using NUnit.Framework; -using Spring.Collections; namespace Spring.Transaction.Interceptor { @@ -10,75 +9,83 @@ namespace Spring.Transaction.Interceptor public class RuleBasedTransactionAttributeTests { [Test] - public void DefaultRule() + public void DefaultRule() { - RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute(); + var rta = new RuleBasedTransactionAttribute(); Assert.IsTrue(rta.RollbackOn(new SystemException())); - //mlp 3/17 changed rollback to rollback on all exceptions. + //mlp 3/17 changed rollback to rollback on all exceptions. Assert.IsTrue(rta.RollbackOn(new ApplicationException())); - Assert.IsTrue( rta.RollbackOn(new TransactionSystemException())); + Assert.IsTrue(rta.RollbackOn(new TransactionSystemException())); } - [Test] - public void RuleForRollbackOnApplicationException() - { - IList list = new LinkedList(); - list.Add(new RollbackRuleAttribute("Spring.Transaction.TransactionSystemException")); - RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute( TransactionPropagation.Required, list ); - Assert.IsTrue( rta.RollbackOn(new SystemException())); - //mlp 3/17 changed rollback to rollback on all exceptions. - Assert.IsTrue( rta.RollbackOn(new ApplicationException())); - Assert.IsTrue(( rta.RollbackOn( new TransactionSystemException()))); - } [Test] - public void RuleForCommitOnUnchecked() + public void RuleForRollbackOnApplicationException() { - IList list = new LinkedList(); - list.Add( new NoRollbackRuleAttribute("System.SystemException")); + var list = new List(); + list.Add(new RollbackRuleAttribute("Spring.Transaction.TransactionSystemException")); + RuleBasedTransactionAttribute + rta = new RuleBasedTransactionAttribute(TransactionPropagation.Required, list); + + Assert.IsTrue(rta.RollbackOn(new SystemException())); + //mlp 3/17 changed rollback to rollback on all exceptions. + Assert.IsTrue(rta.RollbackOn(new ApplicationException())); + Assert.IsTrue((rta.RollbackOn(new TransactionSystemException()))); + } + + [Test] + public void RuleForCommitOnUnchecked() + { + var list = new List(); + list.Add(new NoRollbackRuleAttribute("System.SystemException")); list.Add(new RollbackRuleAttribute("Spring.Transaction.TransactionSystemException")); - RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute( TransactionPropagation.Required, list ); - Assert.IsFalse( rta.RollbackOn(new SystemException())); - Assert.IsTrue( rta.RollbackOn(new TransactionSystemException())); + var rta = new RuleBasedTransactionAttribute(TransactionPropagation.Required, list); + Assert.IsFalse(rta.RollbackOn(new SystemException())); + Assert.IsTrue(rta.RollbackOn(new TransactionSystemException())); } + [Test] - public void RuleForSelectiveRollbackOnCheckedWithString() + public void RuleForSelectiveRollbackOnCheckedWithString() { - IList list = new LinkedList(); - list.Add( new RollbackRuleAttribute("Spring.Transaction.TransactionSystemException")); - RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute( TransactionPropagation.Required, list ); - ruleForSelectionRollbackOnChecked( rta ); + IList list = new List(); + list.Add(new RollbackRuleAttribute("Spring.Transaction.TransactionSystemException")); + var rta = new RuleBasedTransactionAttribute(TransactionPropagation.Required, list); + ruleForSelectionRollbackOnChecked(rta); } + [Test] - public void RuleForSelectiveRollbackOnCheckedWithClass() + public void RuleForSelectiveRollbackOnCheckedWithClass() { - IList list = new LinkedList(); - list.Add( new RollbackRuleAttribute(typeof(TransactionSystemException))); - RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute( TransactionPropagation.Required, list ); - ruleForSelectionRollbackOnChecked( rta ); + var list = new List(); + list.Add(new RollbackRuleAttribute(typeof(TransactionSystemException))); + var rta = new RuleBasedTransactionAttribute(TransactionPropagation.Required, list); + ruleForSelectionRollbackOnChecked(rta); } - private void ruleForSelectionRollbackOnChecked( RuleBasedTransactionAttribute rta ) + + private void ruleForSelectionRollbackOnChecked(RuleBasedTransactionAttribute rta) { Assert.IsTrue(rta.RollbackOn(new SystemException())); - Assert.IsTrue( rta.RollbackOn(new TransactionSystemException())); + Assert.IsTrue(rta.RollbackOn(new TransactionSystemException())); } + [Test] - public void RuleForCommitOnSubclassOfChecked() + public void RuleForCommitOnSubclassOfChecked() { - IList list = new LinkedList(); - list.Add( new RollbackRuleAttribute("System.Data.DataException")); - list.Add( new NoRollbackRuleAttribute("Spring.Transaction.TransactionSystemException")); - RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute( TransactionPropagation.Required, list ); - - Assert.IsTrue( rta.RollbackOn(new SystemException())); - Assert.IsFalse( rta.RollbackOn(new TransactionSystemException())); + var list = new List(); + list.Add(new RollbackRuleAttribute("System.Data.DataException")); + list.Add(new NoRollbackRuleAttribute("Spring.Transaction.TransactionSystemException")); + var rta = new RuleBasedTransactionAttribute(TransactionPropagation.Required, list); + + Assert.IsTrue(rta.RollbackOn(new SystemException())); + Assert.IsFalse(rta.RollbackOn(new TransactionSystemException())); } + [Test] - public void RollbackNever() + public void RollbackNever() { - IList list = new LinkedList(); - list.Add( new NoRollbackRuleAttribute("System.Exception")); - RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute( TransactionPropagation.Required, list ); + var list = new List(); + list.Add(new NoRollbackRuleAttribute("System.Exception")); + var rta = new RuleBasedTransactionAttribute(TransactionPropagation.Required, list); Assert.IsFalse(rta.RollbackOn(new SystemException())); Assert.IsFalse(rta.RollbackOn(new DataException())); diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/CachedSessionTests.cs b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/CachedSessionTests.cs index 3b937130..914f6903 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/CachedSessionTests.cs +++ b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/CachedSessionTests.cs @@ -18,6 +18,7 @@ #endregion +using System.Collections.Generic; using Apache.NMS; using NUnit.Framework; using Spring.Collections; @@ -59,7 +60,7 @@ namespace Spring.Messaging.Nms.Connections private CachedSession CreateCachedSession(ISession targetSession) { - return new CachedSession(targetSession, new LinkedList(), new CachingConnectionFactory()); + return new CachedSession(targetSession, new List(), new CachingConnectionFactory()); } } }