lsyf8 发表于 2018-10-20 09:18:16

深入理解 OWIN 中的 Host 和 Server

using System;  
using System.IO;
  
using System.Threading;
  
using System.Threading.Tasks;
  
using Microsoft.Framework.ConfigurationModel;
  
using Microsoft.Framework.DependencyInjection;
  
using Microsoft.Framework.DependencyInjection.Fallback;
  
using Microsoft.Framework.Logging;
  
using Microsoft.Framework.Runtime;
  

  
namespace Microsoft.AspNet.Hosting
  
{
  
    public class Program
  
    {
  
      private const string HostingIniFile = "Microsoft.AspNet.Hosting.ini";
  
      private readonly IServiceProvider _serviceProvider;
  

  
      public Program(IServiceProvider serviceProvider)
  
      {
  
            _serviceProvider = serviceProvider;
  
      }
  

  
      public void Main(string[] args)
  
      {
  
            var config = new Configuration();
  
            if (File.Exists(HostingIniFile))
  
            {
  
                config.AddIniFile(HostingIniFile);
  
            }
  
            config.AddEnvironmentVariables();
  
            config.AddCommandLine(args);
  

  
            var services = HostingServices.Create(_serviceProvider, config)
  
                .BuildServiceProvider();
  
            var appEnv = services.GetRequiredService();
  
            var hostingEnv = services.GetRequiredService();
  

  
            var context = new HostingContext()
  
            {
  
                Services = services,
  
                Configuration = config,
  
                ServerName = config.Get("server"), // TODO: Key names
  
                ApplicationName = config.Get("app")// TODO: Key names
  
                  ?? appEnv.ApplicationName,
  
                EnvironmentName = hostingEnv.EnvironmentName,
  
            };
  

  
            var engine = services.GetRequiredService();
  
            var loggerFactory = services.GetRequiredService();
  
            var appShutdownService = _serviceProvider.GetRequiredService();
  
            var shutdownHandle = new ManualResetEvent(false);
  
            var serverShutdown = engine.Start(context);
  

  
            appShutdownService.ShutdownRequested.Register(() =>
  
            {
  
                try
  
                {
  
                  serverShutdown.Dispose();
  
                }
  
                catch (Exception ex)
  
                {
  
                  var logger = loggerFactory.Create();
  
                  logger.WriteError("TODO: Dispose threw an exception", ex);
  
                }
  
                shutdownHandle.Set();
  
            });
  

  
            var ignored = Task.Run(() =>
  
            {
  
                Console.WriteLine("Started");
  
                Console.ReadLine();
  
                appShutdownService.RequestShutdown();
  
            });
  

  
            shutdownHandle.WaitOne();
  
      }
  
    }
  
}


页: [1]
查看完整版本: 深入理解 OWIN 中的 Host 和 Server