<PackageReference Include="Castle.Windsor" Version="4.1.1" />

PerWebRequestLifestyleModule

using Castle.MicroKernel.Lifestyle.Scoped; using System; using System.Text; using System.Web; namespace Castle.MicroKernel.Lifestyle { public class PerWebRequestLifestyleModule { private const string key = "castle.per-web-request-lifestyle-cache"; private static bool initialized; public void Dispose() { } public void Init(HttpApplication context) { initialized = true; context.add_EndRequest((EventHandler)Application_EndRequest); } protected void Application_EndRequest(object sender, EventArgs e) { GetScope(sender.get_Context(), false)?.Dispose(); } internal static ILifetimeScope GetScope() { EnsureInitialized(); HttpContext current = HttpContext.get_Current(); if ((int)current == 0) throw new InvalidOperationException("HttpContext.Current is null. PerWebRequestLifestyle can only be used in ASP.Net"); return GetScope(current, true); } internal static ILifetimeScope YieldScope() { HttpContext val = HttpContext.get_Current(); if (val == null) return null; ILifetimeScope scope = GetScope(val, true); if (scope != null) val.get_Items().Remove("castle.per-web-request-lifestyle-cache"); return scope; } private static void EnsureInitialized() { if (initialized) return; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Looks like you forgot to register the http module " + typeof(PerWebRequestLifestyleModule).FullName); stringBuilder.AppendLine("To fix this add"); stringBuilder.AppendLine("<add name=\"PerRequestLifestyle\" type=\"Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor\" />"); stringBuilder.AppendLine("to the <httpModules> section on your web.config."); if (HttpRuntime.get_UsingIntegratedPipeline()) stringBuilder.AppendLine("Windsor also detected you're running IIS in Integrated Pipeline mode. This means that you also need to add the module to the <modules> section under <system.webServer>."); else stringBuilder.AppendLine("If you plan running on IIS in Integrated Pipeline mode, you also need to add the module to the <modules> section under <system.webServer>."); stringBuilder.AppendLine("Alternatively make sure you have Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 assembly in your GAC (it is installed by ASP.NET MVC3 or WebMatrix) and Windsor will be able to register the module automatically without having to add anything to the config file."); throw new ComponentResolutionException(stringBuilder.ToString()); } private static ILifetimeScope GetScope(HttpContext context, bool createIfNotPresent) { ILifetimeScope lifetimeScope = (ILifetimeScope)context.get_Items()["castle.per-web-request-lifestyle-cache"]; if ((lifetimeScope == null) & createIfNotPresent) { lifetimeScope = new DefaultLifetimeScope(new ScopeCache(), null); context.get_Items()["castle.per-web-request-lifestyle-cache"] = lifetimeScope; } return lifetimeScope; } } }