diff --git a/src/LightInject.Web/LightInject.Web.cs b/src/LightInject.Web/LightInject.Web.cs index ef530a2..8df20dd 100644 --- a/src/LightInject.Web/LightInject.Web.cs +++ b/src/LightInject.Web/LightInject.Web.cs @@ -112,6 +112,7 @@ public void Dispose() public class PerWebRequestScopeManager : ScopeManager { private const string Key = "LightInject.Scope"; + private Scope DefaultScope; /// /// Initializes a new instance of the class. @@ -119,6 +120,7 @@ public class PerWebRequestScopeManager : ScopeManager /// The to be associated with this . public PerWebRequestScopeManager(IServiceFactory serviceFactory) : base(serviceFactory) { + DefaultScope = new Scope(this, null); } /// @@ -127,7 +129,13 @@ 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; + } + } } /// @@ -135,16 +143,25 @@ public override Scope CurrentScope /// 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) { @@ -174,4 +191,4 @@ protected override IScopeManager CreateScopeManager(IServiceFactory serviceFacto return new PerWebRequestScopeManager(serviceFactory); } } -} +} \ No newline at end of file