public static EngineSettings Match(this IRunningEngineTable table, HttpContext httpContext) { if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } var httpRequest = httpContext.Request; return(table.Match(httpRequest.Host.ToString(), httpRequest.Path, true)); }
public async Task Invoke(HttpContext httpContext) { _host.Initialize(); var engineSettings = _runningEngineTable.Match(httpContext); if (engineSettings != null) { var engineContext = _host.GetOrCreateEngineContext(engineSettings); var hasPendingTasks = false; using (var scope = engineContext.EnterServiceScope()) { httpContext.Features.Set(engineContext); // 把租户前缀加到 cookie 里 httpContext.Response.Cookies.Append("tenant_prefix", engineSettings.RequestUrlPrefix ?? ""); httpContext.Response.Cookies.Append("tenant_host", engineSettings.RequestUrlHost ?? ""); if (!engineContext.IsActivated) { var semaphore = _semaphores.GetOrAdd(engineSettings.Name, (name) => new SemaphoreSlim(1)); await semaphore.WaitAsync(); try { if (!engineContext.IsActivated) { using (var activatingScope = engineContext.EnterServiceScope()) { var tenantEvents = activatingScope.ServiceProvider.GetServices <IModuleTenantEvents>(); foreach (var tenantEvent in tenantEvents) { await tenantEvent.ActivatingAsync(); } httpContext.Items["BuildPipeline"] = true; foreach (var tenantEvent in tenantEvents.Reverse()) { await tenantEvent.ActivatedAsync(); } } engineContext.IsActivated = true; } } finally { semaphore.Release(); _semaphores.TryRemove(engineSettings.Name, out semaphore); } } await _next.Invoke(httpContext); var deferredTaskEngine = scope.ServiceProvider.GetService <IDeferredTaskEngine>(); hasPendingTasks = deferredTaskEngine?.HasPendingTasks ?? false; } if (hasPendingTasks) { engineContext = _host.GetOrCreateEngineContext(engineSettings); using (var scope = engineContext.EnterServiceScope()) { var deferredTaskEngine = scope.ServiceProvider.GetService <IDeferredTaskEngine>(); var context = new DeferredTaskContext(scope.ServiceProvider); await deferredTaskEngine.ExecuteTasksAsync(context); } } } }