From bdf6174b1065a24877f16bba68921772a9586b48 Mon Sep 17 00:00:00 2001 From: Rodney Chen <rodney.chen@hotmail.com> Date: 星期四, 24 四月 2025 21:01:23 +0800 Subject: [PATCH] 优化了一些已知问题 --- Tiger.Api/Program.cs | 202 +++++++++++++++++++++++++++++--------------------- 1 files changed, 116 insertions(+), 86 deletions(-) diff --git a/Tiger.Api/Program.cs b/Tiger.Api/Program.cs index 57dbf7b..21de323 100644 --- a/Tiger.Api/Program.cs +++ b/Tiger.Api/Program.cs @@ -17,74 +17,103 @@ using Autofac; using Tiger.IBusiness; - - -bool isService = Debugger.IsAttached ? false : Directory.GetCurrentDirectory().ToLower() == @"c:\windows\system32"; - -var pathToContentRoot = AppDomain.CurrentDomain.BaseDirectory; -if (isService) +var begin = DateTime.Now; +try { - var pathToExe = Process.GetCurrentProcess().MainModule.FileName; - pathToContentRoot = Path.GetDirectoryName(pathToExe) + "\\"; -} -var options = new WebApplicationOptions -{ - Args = args, - ContentRootPath = pathToContentRoot -}; + //闈濽I绾跨▼鏈崟鑾峰紓甯稿鐞嗕簨浠� + AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); + //Task 绾跨▼鍐呮湭鎹曡幏寮傚父澶勭悊浜嬩欢 + TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; + + bool isService = Debugger.IsAttached ? false : Directory.GetCurrentDirectory().ToLower() == @"c:\windows\system32"; + + var pathToContentRoot = AppDomain.CurrentDomain.BaseDirectory; + if (isService) + { + var pathToExe = Process.GetCurrentProcess().MainModule.FileName; + pathToContentRoot = Path.GetDirectoryName(pathToExe) + "\\"; + } + + var IsRunAsAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); + //var config = (new ConfigurationBuilder().SetBasePath(pathToContentRoot).AddJsonFile("appsettings.json")).Build(); + var prod = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute)).First() as AssemblyProductAttribute).Product; + var vers = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute)).First() as AssemblyFileVersionAttribute).Version; + var desc = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute)).First() as AssemblyDescriptionAttribute).Description; + Logger.Default.Info($"{prod}(Version {vers}) {desc}"); + ConsoleExt.WriteLine(""); + ConsoleExt.WriteLine($" {prod}(Version {vers}) Base on .Net 6", ConsoleColor.Green); + ConsoleExt.WriteLine(""); + ConsoleExt.Write($" ====== > ===== > ==== >---->--->-->-> > ", ConsoleColor.DarkCyan); + ConsoleExt.Write($"Link Start{(IsRunAsAdmin ? $" As Admin" : "")}", ConsoleColor.Cyan); + ConsoleExt.WriteLine($" < <-<--<---<----< ==== < ===== < ====== ", ConsoleColor.DarkCyan); + Logger.Console.Info($"Begin to load {prod}"); -var builder = WebApplication.CreateBuilder(options); -builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); -builder.Host.ConfigureContainer<ContainerBuilder>(builder => -{ - //AutoFac 閰嶇疆鏂囦欢娉ㄥ叆 - AutoFacContainer.Init(builder); - builder.RegisterBuildCallback(scope => - { - AutoFacContainer.Instance = (IContainer)scope; - //鍒濆鍖朆usiness鐨凙utoFacContainer - //DI.Resolve<IBiz>().SetContainer(AutoFacContainer.Instance = (IContainer)scope); + System.Net.ServicePointManager.DefaultConnectionLimit = 1024; + + var options = new WebApplicationOptions + { + Args = args, + ContentRootPath = pathToContentRoot, + }; + + var builder = WebApplication.CreateBuilder(options); + builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); + builder.Host.ConfigureContainer<ContainerBuilder>(builder => + { + //AutoFac 閰嶇疆鏂囦欢娉ㄥ叆 + AutoFacContainer.Init(builder); + builder.RegisterBuildCallback(scope => + { + AutoFacContainer.Instance = (IContainer)scope; + //鍒濆鍖朆usiness鐨凙utoFacContainer + //DI.Resolve<IBiz>().SetContainer(AutoFacContainer.Instance = (IContainer)scope); + }); + //builder.RegisterType<TestService>().As<ITest>(); + }); + + Logger.Console.Info($"AutoFac container inject successful"); + var startup = new Startup(builder.Configuration); + startup.ConfigureServices(builder.Services); + + var config = (new ConfigurationBuilder().SetBasePath(pathToContentRoot).AddJsonFile("appsettings.json")).Build(); + var urls = config.AsEnumerable().Where(q => q.Key.StartsWith("StartUpSetting:UseUrls") && q.Value != null).Select(q => q.Value).ToArray(); + builder.WebHost.UseUrls(urls); + + builder.WebHost.UseKestrel(opt => + { + // 璁剧疆鏈�澶ц繛鎺ユ暟 + opt.Limits.MaxConcurrentConnections = null; + // 璁剧疆璇锋眰闃熷垪鐨勯暱搴� + opt.Limits.MaxConcurrentUpgradedConnections = null; + opt.Limits.MinRequestBodyDataRate = null; }); - //builder.RegisterType<TestService>().As<ITest>(); -}); -var startup = new Startup(builder.Configuration); -startup.ConfigureServices(builder.Services); -Main(args); -var config = (new ConfigurationBuilder().SetBasePath(pathToContentRoot).AddJsonFile("appsettings.json")).Build(); -var urls = config.AsEnumerable().Where(q => q.Key.StartsWith("StartUpSetting:UseUrls") && q.Value != null).Select(q => q.Value).ToArray(); -var prod = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute)).First() as AssemblyProductAttribute).Product; -builder.WebHost.UseUrls(urls); -builder.WebHost.UseKestrel(opt => -{ - opt.Limits.MinRequestBodyDataRate = null; -}); + if (isService) + { + builder.Host.UseWindowsService(); + Logger.Default.Info("Run Api as Windows Services"); + } + Logger.Console.Info($"Configure WebApplication successful"); + var app = builder.Build(); + Logger.Console.Info($"Build {prod} successful"); + //聽Fetch聽all聽the聽dependencies聽from聽the聽DI聽container聽 + //聽var聽hostLifetime聽=聽app.Services.GetRequiredService<IHostApplicationLifetime>(); + //聽As聽pointed聽out聽by聽DavidFowler,聽IHostApplicationLifetime聽is聽exposed聽directly聽on聽ApplicationBuilder + //聽Call聽Configure(),聽passing聽in聽the聽dependencies + startup.Configure(app, app.Environment); + Logger.Console.Info($"Run {prod} Successful"); + Logger.Console.Info($"Total Elapsed Time: {(DateTime.Now - begin).TotalSeconds:0.000} seconds"); -if (isService) -{ - builder.Host.UseWindowsService(); + app.Run(); + Logger.Console.Info($"{prod} Host is shut down"); } - -var app = builder.Build(); -//聽Fetch聽all聽the聽dependencies聽from聽the聽DI聽container聽 -//聽var聽hostLifetime聽=聽app.Services.GetRequiredService<IHostApplicationLifetime>(); -//聽As聽pointed聽out聽by聽DavidFowler,聽IHostApplicationLifetime聽is聽exposed聽directly聽on聽ApplicationBuilder -//聽Call聽Configure(),聽passing聽in聽the聽dependencies -startup.Configure(app, app.Environment); -Logger.Console.Info($"Run {prod} Host"); - -app.Run(); -Logger.Console.Info($"{prod} Host is shut down"); - - -void Main(string[] args) +catch (System.Exception ex) { - //闈濽I绾跨▼鏈崟鑾峰紓甯稿鐞嗕簨浠� - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); - //Task 绾跨▼鍐呮湭鎹曡幏寮傚父澶勭悊浜嬩欢 - TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; - - CreateWindowsServicesBuilder(args); + Logger.Console.Fatal(ex, "Run {prod} Host Exception"); +} +finally +{ + Logger.Console.Info($"Api Host finally shut down"); } @@ -120,21 +149,22 @@ Logger.Default.Fatal(e.Exception, $"鎹曡幏绾跨▼鍐呮湭澶勭悊寮傚父"); e.SetObserved();//璁剧疆璇ュ紓甯稿凡瀵熻锛堣繖鏍峰鐞嗗悗灏变笉浼氬紩璧风▼搴忓穿婧冿級 } + void CreateWindowsServicesBuilder(string[] args) { try { - //bool isService = Debugger.IsAttached ? false : Directory.GetCurrentDirectory().ToLower() == @"c:\windows\system32"; + bool isService = Debugger.IsAttached ? false : Directory.GetCurrentDirectory().ToLower() == @"c:\windows\system32"; - //var pathToContentRoot = AppDomain.CurrentDomain.BaseDirectory; - //if (isService) - //{ - // var pathToExe = Process.GetCurrentProcess().MainModule.FileName; - // pathToContentRoot = Path.GetDirectoryName(pathToExe) + "\\"; - //} + var pathToContentRoot = AppDomain.CurrentDomain.BaseDirectory; + if (isService) + { + var pathToExe = Process.GetCurrentProcess().MainModule.FileName; + pathToContentRoot = Path.GetDirectoryName(pathToExe) + "\\"; + } var IsRunAsAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); - //var config = (new ConfigurationBuilder().SetBasePath(pathToContentRoot).AddJsonFile("appsettings.json")).Build(); + var config = (new ConfigurationBuilder().SetBasePath(pathToContentRoot).AddJsonFile("appsettings.json")).Build(); var prod = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute)).First() as AssemblyProductAttribute).Product; var vers = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute)).First() as AssemblyFileVersionAttribute).Version; var desc = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute)).First() as AssemblyDescriptionAttribute).Description; @@ -147,24 +177,24 @@ ConsoleExt.WriteLine($" < <-<--<---<----< ==== < ===== < ====== ", ConsoleColor.DarkCyan); Logger.Console.Info($"Run {prod} Host"); //var urls = string.IsNullOrEmpty(config["StartUpSetting:UseUrls"]) ? "http://*:3810" : config["StartUpSetting:UseUrls"]; - //var urls = config.AsEnumerable().Where(q => q.Key.StartsWith("StartUpSetting:UseUrls") && q.Value != null).Select(q => q.Value).ToArray(); - //var host = WebHost.CreateDefaultBuilder(args) - // .UseContentRoot(pathToContentRoot) - // .UseUrls(urls) - // .UseStartup<Startup>() - // .Build(); + var urls = config.AsEnumerable().Where(q => q.Key.StartsWith("StartUpSetting:UseUrls") && q.Value != null).Select(q => q.Value).ToArray(); + var host = WebHost.CreateDefaultBuilder(args) + .UseContentRoot(pathToContentRoot) + .UseUrls(urls) + .UseStartup<Startup>() + .Build(); - //if (isService) - //{ - // host.RunAsApiService(); - // //host.RunAsService(); - //} - //else - //{ - // Logger.Console.Info($"Run {prod} Host"); - // host.Run(); - // Logger.Console.Info($"{prod} Host is shut down"); - //} + if (isService) + { + host.RunAsApiService(); + //host.RunAsService(); + } + else + { + Logger.Console.Info($"Run {prod} Host"); + host.Run(); + Logger.Console.Info($"{prod} Host is shut down"); + } } catch (System.Exception ex) { -- Gitblit v1.9.3