Created
October 18, 2019 06:30
-
-
Save divanvisagie/ac3a94dab1d26d199a64be7ce0a17508 to your computer and use it in GitHub Desktop.
C# Kestrel pipeline branch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Hosting.Builder; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace Swerve | |
{ | |
public static class ApplicationBuilderExtensions | |
{ | |
public static IApplicationBuilder UseBranchForPort(this IApplicationBuilder app, int port, | |
Action<IServiceCollection> servicesConfiguration, Action<IApplicationBuilder> appBuilderConfiguration) | |
{ | |
var webHost = new WebHostBuilder() | |
.UseKestrel() | |
.ConfigureServices(servicesConfiguration) | |
.UseStartup<EmptyStartup>() | |
.Build(); | |
var serviceProvider = webHost.Services; | |
var serverFeatures = webHost.ServerFeatures; | |
var appBuilderFactory = serviceProvider.GetRequiredService<IApplicationBuilderFactory>(); | |
var branchBuilder = appBuilderFactory.CreateBuilder(serverFeatures); | |
var factory = serviceProvider.GetRequiredService<IServiceScopeFactory>(); | |
branchBuilder.Use(async (context, next) => | |
{ | |
using (var scope = factory.CreateScope()) | |
{ | |
context.RequestServices = scope.ServiceProvider; | |
await next(); | |
} | |
}); | |
appBuilderConfiguration(branchBuilder); | |
var branchDelegate = branchBuilder.Build(); | |
return app.MapWhen(x => x.Request.Host.Port == port, builder => | |
{ | |
builder.Use(async (context, next) => | |
{ | |
await branchDelegate(context); | |
}); | |
}); | |
} | |
private class EmptyStartup | |
{ | |
public void ConfigureServices(IServiceCollection services) { } | |
public void Configure(IApplicationBuilder app) { } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment