public static void Main(string[] args) { // Figure out where webroot and contentRoot are for HostingEnvironment string webRoot; string contentRoot; var testPath = Directory.GetCurrentDirectory(); while (true) { if (Directory.Exists(Path.Combine(testPath, "wwwroot"))) { contentRoot = testPath; webRoot = Path.Combine(testPath, "wwwroot"); break; } else { var parent = Directory.GetParent(testPath); if (parent == null) { throw new InvalidOperationException("Unable to discover WebRoot"); } testPath = parent.FullName; } } contentRoot = Directory.GetCurrentDirectory(); // Create a hosting environment var env = new HostingEnvironment { ContentRootPath = contentRoot, ApplicationName = "throwawayx", EnvironmentName = "Development", WebRootPath = webRoot, ContentRootFileProvider = new PhysicalFileProvider(contentRoot), WebRootFileProvider = new PhysicalFileProvider(webRoot), }; // Build configuration var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); var configuration = builder.Build(); // Now imagine the lifetime exists outside of ASP.NET Core. In other words, // pretend that we're really inside of a nested context w/other things running // adjacent to ASP.NET Core. var cb = new ContainerBuilder(); // Just make logging work w/o an IServiceCollection. In my actual project, // just like the outer Autofac scope, logging is configured externally. var loggerFactory = new LoggerFactory().AddConsole(); cb.RegisterInstance(loggerFactory).SingleInstance(); cb.RegisterGeneric(typeof(Logger <>)).As(typeof(ILogger <>)); // Throw something random in the container that should hopefully turn up in // ASP.NET Core's child scope. cb.RegisterType <RootObject>().SingleInstance(); // Build the container var container = cb.Build(); // The point of this object is to flow some stuff into the Startup class's // constructor via DI. Trying to avoid using statics var startupContainer = new StartupHelper(container, env, configuration); var hostBuilder = new WebHostBuilder() .UseKestrel() // .UseContentRoot(Directory.GetCurrentDirectory()) .UseLoggerFactory(loggerFactory) // <-- Please don't deprecate me .ConfigureServices(svc => { // Because how else can I parameterize startup? svc.AddSingleton(startupContainer); }) .UseStartup <Startup>(); var host = hostBuilder.Build(); host.Run(); }
public Startup(StartupHelper container) { Helper = container; }