Skip to content

Instantly share code, notes, and snippets.

@AtsushiSuzuki
Created February 13, 2017 17:55
Show Gist options
  • Save AtsushiSuzuki/9a03da250ab31980d16bb389abaff27f to your computer and use it in GitHub Desktop.
Save AtsushiSuzuki/9a03da250ab31980d16bb389abaff27f to your computer and use it in GitHub Desktop.
ASP.net core: replace DI services after Startup.
using System;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Tests
{
public static class WebHostBuilderExtensions
{
private class DeferredServiceConfigurator : IStartup
{
private IStartup OriginalStartup { get; }
private IServiceProvider ServiceProvider { get; }
private Action<IServiceCollection> ConfigureAction { get; }
public DeferredServiceConfigurator(IStartup originalStartup, IServiceProvider serviceProvider, Action<IServiceCollection> configureAction)
{
this.OriginalStartup = originalStartup;
this.ServiceProvider = serviceProvider;
this.ConfigureAction = configureAction;
}
public void Configure(IApplicationBuilder app)
{
this.OriginalStartup?.Configure(app);
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
this.OriginalStartup?.ConfigureServices(services);
this.ConfigureAction(services);
return services.BuildServiceProvider();
}
}
public static IWebHostBuilder ConfigureServicesDeferred(this IWebHostBuilder builder, Action<IServiceCollection> configureAction)
{
return builder.ConfigureServices(services =>
{
var originalStartupDescription = services.LastOrDefault(s => s.ServiceType == typeof(IStartup));
services.Remove(originalStartupDescription);
services.AddSingleton<IStartup>(serviceProvider =>
{
var startup = (IStartup)(originalStartupDescription.ImplementationInstance
?? originalStartupDescription.ImplementationFactory?.Invoke(serviceProvider)
?? ActivatorUtilities.CreateInstance(serviceProvider, originalStartupDescription.ImplementationType));
return new DeferredServiceConfigurator(startup, serviceProvider, configureAction);
});
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment