using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Umbraco.Core.ObjectResolution { internal abstract class LazyManyObjectsResolverBase : ManyObjectsResolverBase where TResolved : class where TResolver : class { #region Constructors protected LazyManyObjectsResolverBase(ObjectLifetimeScope scope = ObjectLifetimeScope.Application) : base(scope) { } protected LazyManyObjectsResolverBase(HttpContextBase httpContext) : base(httpContext) { } protected LazyManyObjectsResolverBase(IEnumerable> value, ObjectLifetimeScope scope = ObjectLifetimeScope.Application) : this(scope) { AddTypes(value); } protected LazyManyObjectsResolverBase(HttpContextBase httpContext, IEnumerable> value) : this(httpContext) { } #endregion private readonly List> _lazyTypes = new List>(); private bool _hasResolvedTypes = false; /// /// Used for unit tests /// internal bool HasResolvedTypes { get { return _hasResolvedTypes; } } /// /// Once this is called this will resolve all types registered in the lazy list /// protected override IEnumerable InstanceTypes { get { var list = _lazyTypes.Select(x => x.Value).ToArray(); //we need to validate each resolved type now since we could not do it before when inserting the lazy delegates if (!_hasResolvedTypes) { var uniqueList = new List(); foreach (var l in list) { EnsureCorrectType(l); if (uniqueList.Contains(l)) { throw new InvalidOperationException("The Type " + l + " already exists in the collection"); } uniqueList.Add(l); } _hasResolvedTypes = true; } return list; } } protected void AddTypes(IEnumerable> types) { EnsureAddSupport(); EnsureResolutionNotFrozen(); using (GetWriteLock()) { foreach (var t in types) { _lazyTypes.Add(t); } } } /// /// Adds a lazy type to the list /// /// public void AddType(Lazy value) { EnsureAddSupport(); EnsureResolutionNotFrozen(); using (GetWriteLock()) { _lazyTypes.Add(value); } } /// /// Converts the static type added to a lazy type and adds it to the internal list /// /// public override void AddType(Type value) { AddType(new Lazy(() => value)); } /// /// Clears all lazy types /// public override void Clear() { EnsureClearSupport(); EnsureResolutionNotFrozen(); using (GetWriteLock()) { _lazyTypes.Clear(); } } /// /// Does not support removal /// protected override bool SupportsRemove { get { return false; } } /// /// Does not support insert /// protected override bool SupportsInsert { get { return false; } } } }