Core.ObjectsResolution - cleanup + start making things public

This commit is contained in:
Stephan
2013-01-16 13:10:34 -01:00
parent e7b84b1637
commit bfd8e96f71
7 changed files with 352 additions and 131 deletions

View File

@@ -6,30 +6,37 @@ using System.Web;
namespace Umbraco.Core.ObjectResolution
{
internal abstract class ManyObjectsResolverBase<TResolver, TResolved> : ResolverBase<TResolver>
/// <summary>
/// The base class for all many-objects resolvers.
/// </summary>
/// <typeparam name="TResolver">The type of the concrete resolver class.</typeparam>
/// <typeparam name="TResolved">The type of the resolved objects.</typeparam>
public abstract class ManyObjectsResolverBase<TResolver, TResolved> : ResolverBase<TResolver>
where TResolved : class
where TResolver : class
{
private List<TResolved> _applicationInstances = null;
private IEnumerable<TResolved> _applicationInstances = null;
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
private readonly List<Type> _instanceTypes = new List<Type>();
private int _defaultPluginWeight = 10;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects.
/// </summary>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application</param>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected ManyObjectsResolverBase(ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
{
CanResolveBeforeFrozen = false;
if (scope == ObjectLifetimeScope.HttpRequest)
{
if (HttpContext.Current == null)
{
throw new InvalidOperationException("Use alternative constructor accepting a HttpContextBase object in order to set the lifetime scope to HttpRequest when HttpContext.Current is null");
}
CurrentHttpContext = new HttpContextWrapper(HttpContext.Current);
}
@@ -38,50 +45,56 @@ namespace Umbraco.Core.ObjectResolution
}
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects.
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects,
/// with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="httpContext"></param>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected ManyObjectsResolverBase(HttpContextBase httpContext)
{
CanResolveBeforeFrozen = false;
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (httpContext == null)
throw new ArgumentNullException("httpContext");
LifetimeScope = ObjectLifetimeScope.HttpRequest;
CurrentHttpContext = httpContext;
_instanceTypes = new List<Type>();
}
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of objects.
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of object types.
/// </summary>
/// <param name="value">The list of objects.</param>
/// <param name="scope">If set to true will resolve singleton objects which will be created once for the lifetime of the application</param>
/// <param name="value">The list of object types.</param>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected ManyObjectsResolverBase(IEnumerable<Type> value, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(scope)
{
_instanceTypes = new List<Type>(value);
_instanceTypes = value.ToList();
}
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of objects
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of objects,
/// with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="httpContext"></param>
/// <param name="value"></param>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <param name="value">The list of object types.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected ManyObjectsResolverBase(HttpContextBase httpContext, IEnumerable<Type> value)
: this(httpContext)
{
_instanceTypes = new List<Type>(value);
_instanceTypes = value.ToList();
}
#endregion
/// <summary>
/// used internally for special resolvers to be able to resolve objects before resolution is frozen.
/// Gets or sets a value indicating whether the resolver can resolve objects before resolution is frozen.
/// </summary>
/// <remarks>This is false by default and is used for some special internal resolvers.</remarks>
internal bool CanResolveBeforeFrozen { get; set; }
/// <summary>
/// Returns the list of Types registered that instances will be created from
/// Gets the list of types to create instances from.
/// </summary>
protected virtual IEnumerable<Type> InstanceTypes
{
@@ -89,114 +102,144 @@ namespace Umbraco.Core.ObjectResolution
}
/// <summary>
/// Returns the Current HttpContextBase used to construct this object if one exists.
/// If one exists then the LifetimeScope will be ObjectLifetimeScope.HttpRequest
/// Gets or sets the <see cref="HttpContextBase"/> used to initialize this object, if any.
/// </summary>
/// <remarks>If not null, then <c>LifetimeScope</c> will be <c>ObjectLifetimeScope.HttpRequest</c>.</remarks>
protected HttpContextBase CurrentHttpContext { get; private set; }
/// <summary>
/// Returns the ObjectLifetimeScope for created objects
/// Gets or sets the lifetime scope of resolved objects.
/// </summary>
protected ObjectLifetimeScope LifetimeScope { get; private set; }
private int _defaultPluginWeight = 10;
/// <summary>
/// Used in conjunction with GetSortedValues and WeightedPluginAttribute, if any of the objects
/// being resolved do not contain the WeightedPluginAttribute then this will be the default weight applied
/// to the object.
/// Gets the resolved object instances, sorted by weight.
/// </summary>
/// <returns>The sorted resolved object instances.</returns>
/// <remarks>
/// <para>The order is based upon the <c>WeightedPluginAttribute</c> and <c>DefaultPluginWeight</c>.</para>
/// <para>Weights are sorted ascendingly (lowest weights come first).</para>
/// </remarks>
protected IEnumerable<TResolved> GetSortedValues()
{
var values = Values.ToList();
// FIXME - so we're re-sorting each time?
values.Sort((f1, f2) => GetObjectWeight(f1).CompareTo(GetObjectWeight(f2)));
return values;
}
/// <summary>
/// Gets or sets the default type weight.
/// </summary>
/// <remarks>Determines the weight of types that do not have a <c>WeightedPluginAttribute</c> set on
/// them, when calling <c>GetSortedValues</c>.</remarks>
protected virtual int DefaultPluginWeight
{
get { return _defaultPluginWeight; }
set { _defaultPluginWeight = value; }
}
/// <summary>
/// If a resolver requries that objects are resolved with a specific order using the WeightedPluginAttribute
/// then this method should be used instead of the Values property.
/// </summary>
/// <returns></returns>
protected IEnumerable<TResolved> GetSortedValues()
int GetObjectWeight(object o)
{
var vals = Values.ToList();
//ensure they are sorted
vals.Sort((f1, f2) =>
{
Func<object, int> getWeight = o =>
{
var weightAttribute = f1.GetType().GetCustomAttribute<WeightedPluginAttribute>(true);
return weightAttribute != null ? weightAttribute.Weight : DefaultPluginWeight;
};
return getWeight(f1).CompareTo(getWeight(f2));
});
return vals;
}
var type = o.GetType();
var attr = type.GetCustomAttribute<WeightedPluginAttribute>(true);
return attr == null ? DefaultPluginWeight : attr.Weight;
}
/// <summary>
/// Returns the list of new object instances.
/// Gets the resolved object instances.
/// </summary>
/// <exception cref="InvalidOperationException"><c>CanResolveBeforeFrozen</c> is false, and resolution is not frozen.</exception>
protected IEnumerable<TResolved> Values
{
get
{
//We cannot return values unless resolution is locked
// cannot return values unless resolution is frozen, or we can
if (!CanResolveBeforeFrozen && !Resolution.IsFrozen)
throw new InvalidOperationException("Values cannot be returned until Resolution is frozen");
throw new InvalidOperationException("Values cannot be returned until resolution is frozen");
// note: we apply .ToArray() to the output of CreateInstance() because that is an IEnumerable that
// comes from the PluginManager we want to be _sure_ that it's not a Linq of some sort, but the
// instances have actually been instanciated when we return.
switch (LifetimeScope)
{
case ObjectLifetimeScope.HttpRequest:
//create new instances per HttpContext, this means we'll lazily create them and once created, cache them in the HttpContext
//create new instances per application, this means we'll lazily create them and once created, cache them
// create new instances per HttpContext
var key = this.GetType().FullName; // use full type name as key
using (var l = new UpgradeableReadLock(_lock))
{
//check if the items contain the key (based on the full type name)
if (CurrentHttpContext.Items[this.GetType().FullName] == null)
// create if not already there
if (CurrentHttpContext.Items[key] == null)
{
l.UpgradeToWriteLock();
//add the items to the context items (based on full type name)
CurrentHttpContext.Items[this.GetType().FullName] = new List<TResolved>(CreateInstances());
CurrentHttpContext.Items[key] = CreateInstances().ToArray();
}
return (List<TResolved>)CurrentHttpContext.Items[this.GetType().FullName];
return (List<TResolved>)CurrentHttpContext.Items[key];
}
case ObjectLifetimeScope.Application:
//create new instances per application, this means we'll lazily create them and once created, cache them
// create new instances per application
using(var l = new UpgradeableReadLock(_lock))
{
// create if not already there
if (_applicationInstances == null)
{
l.UpgradeToWriteLock();
_applicationInstances = new List<TResolved>(CreateInstances());
_applicationInstances = CreateInstances().ToArray();
}
return _applicationInstances;
}
case ObjectLifetimeScope.Transient:
default:
//create new instances each time
return CreateInstances();
// create new instances each time
return CreateInstances().ToArray();
}
}
}
/// <summary>
/// Creates the object instances for the types contained in the types collection.
/// </summary>
/// <returns>A list of objects of type <typeparamref name="TResolved"/>.</returns>
protected virtual IEnumerable<TResolved> CreateInstances()
{
return PluginManager.Current.CreateInstances<TResolved>(InstanceTypes);
}
}
/// <summary>
/// Ensures that a type is a valid type for the resolver.
/// </summary>
/// <param name="value">The type to test.</param>
/// <exception cref="InvalidOperationException"> the type is not a valid type for the resolver.</exception>
protected void EnsureCorrectType(Type value)
{
if (!TypeHelper.IsTypeAssignableFrom<TResolved>(value))
throw new InvalidOperationException(string.Format(
"Type {0} is not an acceptable type for resolver {1}.", value.FullName, this.GetType().FullName));
}
#region Types collection manipulation
/// <summary>
/// Removes a type.
/// </summary>
/// <param name="value">The type to remove.</param>
/// <exception cref="InvalidOperationException">the resolver does not support removing types, or
/// the type is not a valid type for the resolver.</exception>
public virtual void RemoveType(Type value)
{
EnsureRemoveSupport();
EnsureResolutionNotFrozen();
using (GetWriteLock())
using (var l = new UpgradeableReadLock(_lock))
{
EnsureCorrectType(value);
l.UpgradeToWriteLock();
_instanceTypes.Remove(value);
}
}
@@ -204,114 +247,203 @@ namespace Umbraco.Core.ObjectResolution
/// <summary>
/// Removes a type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="T">The type to remove.</typeparam>
/// <exception cref="InvalidOperationException">the resolver does not support removing types, or
/// the type is not a valid type for the resolver.</exception>
public void RemoveType<T>()
{
RemoveType(typeof (T));
RemoveType(typeof(T));
}
/// <summary>
/// protected method allow the inheritor to add many types at once
/// Adds types.
/// </summary>
/// <param name="types"></param>
/// <param name="types">The types to add.</param>
/// <remarks>The types are appended at the end of the list.</remarks>
/// <exception cref="InvalidOperationException">the resolver does not support adding types, or
/// a type is not a valid type for the resolver, or a type is already in the collection of types.</exception>
protected void AddTypes(IEnumerable<Type> types)
{
EnsureAddSupport();
EnsureResolutionNotFrozen();
using (GetWriteLock())
using (new WriteLock(_lock))
{
foreach(var t in types)
{
EnsureCorrectType(t);
if (InstanceTypes.Contains(t))
{
throw new InvalidOperationException("The Type " + t + " already exists in the collection");
};
throw new InvalidOperationException(string.Format(
"Type {0} is already in the collection of types.", t.FullName));
}
_instanceTypes.Add(t);
}
}
}
/// <summary>
/// Adds a Type to the end of the list.
/// Adds a type.
/// </summary>
/// <param name="value">The object to be added.</param>
/// <param name="value">The type to add.</param>
/// <remarks>The type is appended at the end of the list.</remarks>
/// <exception cref="InvalidOperationException">the resolver does not support adding types, or
/// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception>
public virtual void AddType(Type value)
{
EnsureAddSupport();
EnsureResolutionNotFrozen();
using (GetWriteLock())
using (var l = new UpgradeableReadLock(_lock))
{
EnsureCorrectType(value);
if (InstanceTypes.Contains(value))
{
throw new InvalidOperationException("The Type " + value + " already exists in the collection");
};
throw new InvalidOperationException(string.Format(
"Type {0} is already in the collection of types.", value.FullName));
}
l.UpgradeToWriteLock();
_instanceTypes.Add(value);
}
}
/// <summary>
/// Adds a Type to the end of the list.
/// Adds a type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="T">The type to add.</typeparam>
/// <remarks>The type is appended at the end of the list.</remarks>
/// <exception cref="InvalidOperationException">the resolver does not support adding types, or
/// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception>
public void AddType<T>()
{
AddType(typeof (T));
AddType(typeof(T));
}
/// <summary>
/// Clears the list.
/// Clears the list of types.
/// </summary>
/// <exception cref="InvalidOperationException">the resolver does not support clearing types.</exception>
public virtual void Clear()
{
EnsureClearSupport();
EnsureResolutionNotFrozen();
using (GetWriteLock())
using (new WriteLock(_lock))
{
_instanceTypes.Clear();
}
}
/// <summary>
/// Inserts a Type at the specified index.
/// Inserts a type at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which the object should be inserted.</param>
/// <param name="value">The object to insert.</param>
/// <param name="index">The zero-based index at which the type should be inserted.</param>
/// <param name="value">The type to insert.</param>
/// <exception cref="InvalidOperationException">the resolver does not support inserting types, or
/// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
public virtual void InsertType(int index, Type value)
{
EnsureInsertSupport();
EnsureResolutionNotFrozen();
using (var l = GetWriteLock())
using (var l = new UpgradeableReadLock(_lock))
{
EnsureCorrectType(value);
if (InstanceTypes.Contains(value))
{
throw new InvalidOperationException("The Type " + value + " already exists in the collection");
};
throw new InvalidOperationException(string.Format(
"Type {0} is already in the collection of types.", value.FullName));
}
l.UpgradeToWriteLock();
_instanceTypes.Insert(index, value);
}
}
/// <summary>
/// Inserts a Type at the specified index.
/// Inserts a type at the specified index.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="index"></param>
/// <typeparam name="T">The type to insert.</typeparam>
/// <param name="index">The zero-based index at which the type should be inserted.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
public void InsertType<T>(int index)
{
InsertType(index, typeof (T));
InsertType(index, typeof(T));
}
/// Inserts a type before a specified, already existing type.
/// </summary>
/// <param name="existingType">The existing type before which to insert.</param>
/// <param name="value">The type to insert.</param>
/// <exception cref="InvalidOperationException">the resolver does not support inserting types, or
/// one of the types is not a valid type for the resolver, or the existing type is not in the collection,
/// or the new type is already in the collection of types.</exception>
public virtual void InsertTypeBefore(Type existingType, Type value)
{
EnsureInsertSupport();
EnsureResolutionNotFrozen();
using (var l = new UpgradeableReadLock(_lock))
{
EnsureCorrectType(existingType);
EnsureCorrectType(value);
if (!InstanceTypes.Contains(existingType))
{
throw new InvalidOperationException(string.Format(
"Type {0} is not in the collection of types.", existingType.FullName));
}
if (InstanceTypes.Contains(value))
{
throw new InvalidOperationException(string.Format(
"Type {0} is already in the collection of types.", value.FullName));
}
int index = InstanceTypes.IndexOf(existingType);
l.UpgradeToWriteLock();
_instanceTypes.Insert(index, value);
}
}
/// <summary>
/// Inserts a type before a specified, already existing type.
/// </summary>
/// <typeparam name="Texisting">The existing type before which to insert.</typeparam>
/// <typeparam name="T">The type to insert.</typeparam>
/// <exception cref="InvalidOperationException">the resolver does not support inserting types, or
/// one of the types is not a valid type for the resolver, or the existing type is not in the collection,
/// or the new type is already in the collection of types.</exception>
public void InsertTypeBefore<Texisting, T>()
{
InsertTypeBefore(typeof(Texisting), typeof(T));
}
/// <summary>
/// Returns a value indicating whether the specified type is already in the collection of types.
/// </summary>
/// <param name="value">The type to look for.</param>
/// <returns>A value indicating whether the type is already in the collection of types.</returns>
public virtual bool ContainsType(Type value)
{
using (new ReadLock(_lock))
{
return _instanceTypes.Contains(value);
}
}
/// <summary>
/// Returns a value indicating whether the specified type is already in the collection of types.
/// </summary>
/// <typeparam name="T">The type to look for.</typeparam>
/// <returns>A value indicating whether the type is already in the collection of types.</returns>
public bool ContainsType<T>()
{
return ContainsType(typeof(T));
}
#endregion
/// <summary>
/// Returns a WriteLock to use when modifying collections
/// </summary>
@@ -366,16 +498,6 @@ namespace Umbraco.Core.ObjectResolution
throw new InvalidOperationException("This resolver does not support Inserting new types");
}
/// <summary>
/// Throws an exception if the type is not of the TResolved type
/// </summary>
/// <param name="t"></param>
protected void EnsureCorrectType(Type t)
{
if (!TypeHelper.IsTypeAssignableFrom<TResolved>(t))
throw new InvalidOperationException("The resolver " + this.GetType() + " can only accept types of " + typeof(TResolved) + ". The Type passed in to this method is " + t);
}
protected virtual bool SupportsAdd
{
get { return true; }