RequestContext
using Stashbox.Utils;
using Stashbox.Utils.Data;
using System;
using System.Linq;
using System.Runtime.CompilerServices;
namespace Stashbox.Resolution
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
internal class RequestContext : IInternalRequestContext, IRequestContext
{
public static readonly RequestContext Empty = new RequestContext(null);
private readonly Tree<object> excludedInstances = new Tree<object>();
private readonly Tree<object> perRequestInstances = new Tree<object>();
[System.Runtime.CompilerServices.Nullable(new byte[] {
2,
1
})]
private readonly object[] overrides;
public static RequestContext FromOverrides([System.Runtime.CompilerServices.Nullable(new byte[] {
2,
1
})] object[] overrides)
{
return new RequestContext(overrides);
}
public static RequestContext Begin()
{
return new RequestContext(null);
}
private RequestContext([System.Runtime.CompilerServices.Nullable(new byte[] {
2,
1
})] 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;
}
[return: System.Runtime.CompilerServices.Nullable(2)]
public object GetDependencyOverrideOrDefault(Type dependencyType)
{
object[] array = overrides;
if (array == null)
return null;
return array.FirstOrDefault(dependencyType.IsInstanceOfType);
}
[System.Runtime.CompilerServices.NullableContext(2)]
public TResult GetDependencyOverrideOrDefault<TResult>()
{
return (TResult)GetDependencyOverrideOrDefault(typeof(TResult));
}
public object[] GetOverrides()
{
return overrides ?? Constants.EmptyArray<object>();
}
public bool IsInstanceExcludedFromTracking(object instance)
{
object orDefault = excludedInstances.GetOrDefault(instance.GetHashCode());
if (orDefault != null)
return orDefault == instance;
return false;
}
public TInstance ExcludeFromTracking<TInstance>(TInstance value) where TInstance : class
{
excludedInstances.Add(value.GetHashCode(), (object)value);
return value;
}
}
}