Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions src/LightInject.Web/LightInject.Web.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,15 @@ public void Dispose()
public class PerWebRequestScopeManager : ScopeManager
{
private const string Key = "LightInject.Scope";
private Scope DefaultScope;

/// <summary>
/// Initializes a new instance of the <see cref="PerWebRequestScopeManager"/> class.
/// </summary>
/// <param name="serviceFactory">The <see cref="IServiceFactory"/> to be associated with this <see cref="ScopeManager"/>.</param>
public PerWebRequestScopeManager(IServiceFactory serviceFactory) : base(serviceFactory)
{
DefaultScope = new Scope(this, null);
}

/// <summary>
Expand All @@ -127,24 +129,39 @@ public PerWebRequestScopeManager(IServiceFactory serviceFactory) : base(serviceF
public override Scope CurrentScope
{
get { return GetOrAddScope(); }
set { HttpContext.Current.Items[Key] = value; }
set
{
if (HttpContext.Current != null)
{
HttpContext.Current.Items[Key] = value;
}
}
}

/// <summary>
/// Ends the scope associated with the current <see cref="HttpContext"/>.
/// </summary>
public static void EndContextScope()
{
var scope = (Scope)HttpContext.Current.Items[Key];
if (scope != null)
if (HttpContext.Current != null)
{
scope.Dispose();
HttpContext.Current.Items[Key] = null;
var scope = (Scope)HttpContext.Current.Items[Key];
if (scope != null)
{
scope.Dispose();
HttpContext.Current.Items[Key] = null;
}
}
}

private Scope GetOrAddScope()
{
// use global scope if httpcontext isn't set - this will happen for background jobs
if (HttpContext.Current == null)
{
return DefaultScope;
}

var scope = (Scope)HttpContext.Current.Items[Key];
if (scope == null)
{
Expand Down Expand Up @@ -174,4 +191,4 @@ protected override IScopeManager CreateScopeManager(IServiceFactory serviceFacto
return new PerWebRequestScopeManager(serviceFactory);
}
}
}
}