ASP.NET 5 / MVC 6 Console Hosted App

后端 未结 2 2055
难免孤独
难免孤独 2020-12-18 11:04

In MVC5, I had a console application that would use Microsoft.Owin.Hosting.WebApp.Start(...) to host a bunch of controllers that would be dynamically loaded from assemblies

2条回答
  •  余生分开走
    2020-12-18 11:44

    Katana's WebApp static class has been replaced by WebHostBuilder, that offers a much more flexible approach: https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/WebHostBuilder.cs.

    You've probably already used this API without realizing it, as it's the component used by the hosting block when you register a new web command in your project.json (e.g Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:54540) and run it using dnx (e.g dnx . web):

    namespace Microsoft.AspNet.Hosting
    {
        public class Program
        {
            private const string HostingIniFile = "Microsoft.AspNet.Hosting.ini";
            private const string ConfigFileKey = "config";
    
            private readonly IServiceProvider _serviceProvider;
    
            public Program(IServiceProvider serviceProvider)
            {
                _serviceProvider = serviceProvider;
            }
    
            public void Main(string[] args)
            {
                // Allow the location of the ini file to be specified via a --config command line arg
                var tempBuilder = new ConfigurationBuilder().AddCommandLine(args);
                var tempConfig = tempBuilder.Build();
                var configFilePath = tempConfig[ConfigFileKey] ?? HostingIniFile;
    
                var appBasePath = _serviceProvider.GetRequiredService().ApplicationBasePath;
                var builder = new ConfigurationBuilder(appBasePath);
                builder.AddIniFile(configFilePath, optional: true);
                builder.AddEnvironmentVariables();
                builder.AddCommandLine(args);
                var config = builder.Build();
    
                var host = new WebHostBuilder(_serviceProvider, config).Build();
                using (host.Start())
                {
                    Console.WriteLine("Started");
                    var appShutdownService = host.ApplicationServices.GetRequiredService();
                    Console.CancelKeyPress += (sender, eventArgs) =>
                    {
                        appShutdownService.RequestShutdown();
                        // Don't terminate the process immediately, wait for the Main thread to exit gracefully.
                        eventArgs.Cancel = true;
                    };
                    appShutdownService.ShutdownRequested.WaitHandle.WaitOne();
                }
            }
        }
    }
    

    https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/Program.cs

提交回复
热议问题