Skip to content

Instantly share code, notes, and snippets.

@divanvisagie
Created October 18, 2019 06:30
Show Gist options
  • Save divanvisagie/ac3a94dab1d26d199a64be7ce0a17508 to your computer and use it in GitHub Desktop.
Save divanvisagie/ac3a94dab1d26d199a64be7ce0a17508 to your computer and use it in GitHub Desktop.
C# Kestrel pipeline branch
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