Last active
March 12, 2021 12:52
-
-
Save abdusco/08ca77b35ee5a79489a9edac63be4223 to your computer and use it in GitHub Desktop.
Execute ConfigureServices without IWebHostBuilder
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
public static class HostBuilderExtensions | |
{ | |
public static IHostBuilder UseStartup<TStartup>(this IHostBuilder hostBuilder) | |
where TStartup : class => | |
hostBuilder.ConfigureServices((ctx, sc) => | |
{ | |
var startupType = typeof(TStartup); | |
var startupArgs = startupType | |
.GetConstructors().First() | |
.GetParameters() | |
.Select(p => | |
{ | |
if (typeof(IHostEnvironment).IsAssignableFrom(p.ParameterType)) | |
return ctx.HostingEnvironment as object; | |
if (typeof(IConfiguration).IsAssignableFrom(p.ParameterType)) | |
return ctx.Configuration as object; | |
return null; | |
}).ToArray(); | |
var startup = Activator.CreateInstance(typeof(TStartup), startupArgs); | |
startupType | |
.GetMethod(nameof(IStartup.ConfigureServices), new[] {typeof(IServiceCollection)}) | |
?.Invoke(startup, new[] {sc}); | |
}); | |
} |
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 System.Linq; | |
using Hangfire; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
namespace MultiContextWebApp | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
if (args.Contains("--worker")) | |
{ | |
CreateConsoleHostBuilder(args).Build().Run(); | |
return; | |
} | |
CreateHostBuilder(args).Build().Run(); | |
} | |
public static IHostBuilder CreateConsoleHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.UseStartup<Startup>() | |
.ConfigureServices(collection => collection.AddHangfireServer()) | |
.UseConsoleLifetime(); | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment