RequestContext
using Stashbox.Utils;
using Stashbox.Utils.Data;
using System;
using System.Linq;
namespace Stashbox.Resolution
{
internal class RequestContext : IPerRequestInstanceHolder, IRequestContext
{
public static readonly RequestContext Empty = new RequestContext(null);
private readonly Tree<object> perRequestInstances = new Tree<object>();
private readonly object[] overrides;
public static RequestContext FromOverrides(object[] overrides)
{
return new RequestContext(overrides);
}
public static RequestContext Begin()
{
return new RequestContext(null);
}
private RequestContext(object[] overrides = null)
{
this.overrides = overrides;
}
public object GetOrAddInstance(int key, Func<IResolutionScope, IRequestContext, object> factory, IResolutionScope scope)
{
object orDefault = perRequestInstances.GetOrDefault(key);
if (orDefault != null)
return orDefault;
orDefault = factory(scope, this);
perRequestInstances.Add(key, orDefault);
return orDefault;
}
public object GetDependencyOverrideOrDefault(Type dependencyType)
{
object[] array = overrides;
if (array == null)
return null;
return array.FirstOrDefault(dependencyType.IsInstanceOfType);
}
public TResult GetDependencyOverrideOrDefault<TResult>()
{
return (TResult)GetDependencyOverrideOrDefault(typeof(TResult));
}
public object[] GetOverrides()
{
return overrides ?? Constants.EmptyArray<object>();
}
}
}