From 777c3ddd7a69289d2434acf16b90c7db2e8dc36f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Halil=20=C4=B0brahim=20Kalkan?= Date: Mon, 25 Oct 2021 14:50:23 +0300 Subject: [PATCH 01/13] Use new hosting model for the MVC app. --- .../Program.cs | 21 +++++++++---------- .../Startup.cs | 18 ---------------- 2 files changed, 10 insertions(+), 29 deletions(-) delete mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Startup.cs diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs index e6d0635c7c9..3cc35d42917 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs @@ -1,6 +1,8 @@ using System; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -29,7 +31,14 @@ public static int Main(string[] args) try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + builder.Services.AddApplication(); + var app = builder.Build(); + app.InitializeApplication(); + app.Run(); return 0; } catch (Exception ex) @@ -42,15 +51,5 @@ public static int Main(string[] args) Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Startup.cs deleted file mode 100644 index 5bacb0f77eb..00000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Startup.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName.Web -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app) - { - app.InitializeApplication(); - } - } -} From 2437e3e627622d8651c732f9b6998549cfc6c447 Mon Sep 17 00:00:00 2001 From: maliming Date: Tue, 14 Dec 2021 10:28:02 +0800 Subject: [PATCH 02/13] Use new hosting model for the app template. --- .../Program.cs | 77 +++++++++---------- .../Startup.cs | 19 ----- .../Program.cs | 77 +++++++++---------- .../Startup.cs | 19 ----- .../Program.cs | 77 +++++++++---------- .../Startup.cs | 20 ----- .../Program.cs | 77 +++++++++---------- .../Startup.cs | 20 ----- .../Program.cs | 77 +++++++++---------- .../Startup.cs | 18 ----- .../Menus/MyProjectNameMenuContributor.cs | 4 +- .../Program.cs | 77 +++++++++---------- .../Startup.cs | 19 ----- .../Program.cs | 72 ++++++++--------- 14 files changed, 266 insertions(+), 387 deletions(-) delete mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Startup.cs delete mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Startup.cs delete mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs delete mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Startup.cs delete mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Startup.cs delete mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Startup.cs diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs index 5ec34165698..a64b17a3f9f 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs @@ -1,56 +1,55 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; -namespace MyCompanyName.MyProjectName.Blazor.Server.Tiered +namespace MyCompanyName.MyProjectName.Blazor.Server.Tiered; + +public class Program { - public class Program + public static int Main(string[] args) { - public static int Main(string[] args) - { - Log.Logger = new LoggerConfiguration() + Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) - .Enrich.FromLogContext() - .WriteTo.Async(c => c.File("Logs/logs.txt")) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); - - try - { - Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); - return 0; - } - catch (Exception ex) - { - Log.Fatal(ex, "Host terminated unexpectedly!"); - return 1; - } - finally - { - Log.CloseAndFlush(); - } - } + .CreateLogger(); - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) + try + { + Log.Information("Starting web host."); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); + builder.Services.AddApplication(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + app.InitializeApplication(); + app.Run(); + return 0; + } + catch (Exception ex) + { + Log.Fatal(ex, "Host terminated unexpectedly!"); + return 1; + } + finally + { + Log.CloseAndFlush(); + } } } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Startup.cs deleted file mode 100644 index c1624c69e82..00000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Startup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName.Blazor.Server.Tiered -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.InitializeApplication(); - } - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs index 636f823d179..ef9b6dcf353 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs @@ -1,56 +1,55 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; -namespace MyCompanyName.MyProjectName.Blazor.Server +namespace MyCompanyName.MyProjectName.Blazor.Server; + +public class Program { - public class Program + public static int Main(string[] args) { - public static int Main(string[] args) - { - Log.Logger = new LoggerConfiguration() + Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) - .Enrich.FromLogContext() - .WriteTo.Async(c => c.File("Logs/logs.txt")) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); - - try - { - Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); - return 0; - } - catch (Exception ex) - { - Log.Fatal(ex, "Host terminated unexpectedly!"); - return 1; - } - finally - { - Log.CloseAndFlush(); - } - } + .CreateLogger(); - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) + try + { + Log.Information("Starting web host."); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); + builder.Services.AddApplication(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + app.InitializeApplication(); + app.Run(); + return 0; + } + catch (Exception ex) + { + Log.Fatal(ex, "Host terminated unexpectedly!"); + return 1; + } + finally + { + Log.CloseAndFlush(); + } } } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Startup.cs deleted file mode 100644 index 309255b725d..00000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Startup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName.Blazor.Server -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.InitializeApplication(); - } - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs index e16edddb927..e6f48c54c2c 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs @@ -1,56 +1,55 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; -namespace MyCompanyName.MyProjectName +namespace MyCompanyName.MyProjectName; + +public class Program { - public class Program + public static int Main(string[] args) { - public static int Main(string[] args) - { - Log.Logger = new LoggerConfiguration() + Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) - .Enrich.FromLogContext() - .WriteTo.Async(c => c.File("Logs/logs.txt")) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); - - try - { - Log.Information("Starting MyCompanyName.MyProjectName.HttpApi.Host."); - CreateHostBuilder(args).Build().Run(); - return 0; - } - catch (Exception ex) - { - Log.Fatal(ex, "Host terminated unexpectedly!"); - return 1; - } - finally - { - Log.CloseAndFlush(); - } - } + .CreateLogger(); - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) + try + { + Log.Information("Starting MyCompanyName.MyProjectName.HttpApi.Host."); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); + builder.Services.AddApplication(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + app.InitializeApplication(); + app.Run(); + return 0; + } + catch (Exception ex) + { + Log.Fatal(ex, "Host terminated unexpectedly!"); + return 1; + } + finally + { + Log.CloseAndFlush(); + } } } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs deleted file mode 100644 index 644425b2744..00000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs index e16edddb927..e6f48c54c2c 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs @@ -1,56 +1,55 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; -namespace MyCompanyName.MyProjectName +namespace MyCompanyName.MyProjectName; + +public class Program { - public class Program + public static int Main(string[] args) { - public static int Main(string[] args) - { - Log.Logger = new LoggerConfiguration() + Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) - .Enrich.FromLogContext() - .WriteTo.Async(c => c.File("Logs/logs.txt")) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); - - try - { - Log.Information("Starting MyCompanyName.MyProjectName.HttpApi.Host."); - CreateHostBuilder(args).Build().Run(); - return 0; - } - catch (Exception ex) - { - Log.Fatal(ex, "Host terminated unexpectedly!"); - return 1; - } - finally - { - Log.CloseAndFlush(); - } - } + .CreateLogger(); - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) + try + { + Log.Information("Starting MyCompanyName.MyProjectName.HttpApi.Host."); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); + builder.Services.AddApplication(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + app.InitializeApplication(); + app.Run(); + return 0; + } + catch (Exception ex) + { + Log.Fatal(ex, "Host terminated unexpectedly!"); + return 1; + } + finally + { + Log.CloseAndFlush(); + } } } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Startup.cs deleted file mode 100644 index 644425b2744..00000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Startup.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs index 8a57ded1113..499c2e2b41a 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs @@ -1,56 +1,55 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; -namespace MyCompanyName.MyProjectName +namespace MyCompanyName.MyProjectName; + +public class Program { - public class Program + public static int Main(string[] args) { - public static int Main(string[] args) - { - Log.Logger = new LoggerConfiguration() + Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) - .Enrich.FromLogContext() - .WriteTo.Async(c => c.File("Logs/logs.txt")) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); - - try - { - Log.Information("Starting MyCompanyName.MyProjectName.IdentityServer."); - CreateHostBuilder(args).Build().Run(); - return 0; - } - catch (Exception ex) - { - Log.Fatal(ex, "MyCompanyName.MyProjectName.IdentityServer terminated unexpectedly!"); - return 1; - } - finally - { - Log.CloseAndFlush(); - } - } + .CreateLogger(); - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) + try + { + Log.Information("Starting MyCompanyName.MyProjectName.IdentityServer."); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); + builder.Services.AddApplication(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + app.InitializeApplication(); + app.Run(); + return 0; + } + catch (Exception ex) + { + Log.Fatal(ex, "MyCompanyName.MyProjectName.IdentityServer terminated unexpectedly!"); + return 1; + } + finally + { + Log.CloseAndFlush(); + } } } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Startup.cs deleted file mode 100644 index 7fd62325bd1..00000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Startup.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app) - { - app.InitializeApplication(); - } - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Menus/MyProjectNameMenuContributor.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Menus/MyProjectNameMenuContributor.cs index 47298887a45..2ac495d63d5 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Menus/MyProjectNameMenuContributor.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Menus/MyProjectNameMenuContributor.cs @@ -50,7 +50,7 @@ private Task ConfigureMainMenuAsync(MenuConfigurationContext context) order: 0 ) ); - + if (MultiTenancyConsts.IsEnabled) { administration.SetSubItemOrder(TenantManagementMenuNames.GroupName, 1); @@ -59,7 +59,7 @@ private Task ConfigureMainMenuAsync(MenuConfigurationContext context) { administration.TryRemoveMenuItem(TenantManagementMenuNames.GroupName); } - + administration.SetSubItemOrder(IdentityMenuNames.GroupName, 2); administration.SetSubItemOrder(SettingManagementMenuNames.GroupName, 3); diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs index e6d0635c7c9..cdb4a395cc3 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs @@ -1,56 +1,55 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; -namespace MyCompanyName.MyProjectName.Web +namespace MyCompanyName.MyProjectName.Web; + +public class Program { - public class Program + public static int Main(string[] args) { - public static int Main(string[] args) - { - Log.Logger = new LoggerConfiguration() + Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) - .Enrich.FromLogContext() - .WriteTo.Async(c => c.File("Logs/logs.txt")) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); - - try - { - Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); - return 0; - } - catch (Exception ex) - { - Log.Fatal(ex, "Host terminated unexpectedly!"); - return 1; - } - finally - { - Log.CloseAndFlush(); - } - } + .CreateLogger(); - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) + try + { + Log.Information("Starting web host."); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); + builder.Services.AddApplication(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + app.InitializeApplication(); + app.Run(); + return 0; + } + catch (Exception ex) + { + Log.Fatal(ex, "Host terminated unexpectedly!"); + return 1; + } + finally + { + Log.CloseAndFlush(); + } } } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Startup.cs deleted file mode 100644 index 9428c741149..00000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Startup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName.Web -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs index 3cc35d42917..cdb4a395cc3 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs @@ -1,55 +1,55 @@ using System; using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; -namespace MyCompanyName.MyProjectName.Web +namespace MyCompanyName.MyProjectName.Web; + +public class Program { - public class Program + public static int Main(string[] args) { - public static int Main(string[] args) - { - Log.Logger = new LoggerConfiguration() + Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) - .Enrich.FromLogContext() - .WriteTo.Async(c => c.File("Logs/logs.txt")) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); - try - { - Log.Information("Starting web host."); - var builder = WebApplication.CreateBuilder(args); - builder.Host.AddAppSettingsSecretsJson() - .UseAutofac() - .UseSerilog(); - builder.Services.AddApplication(); - var app = builder.Build(); - app.InitializeApplication(); - app.Run(); - return 0; - } - catch (Exception ex) - { - Log.Fatal(ex, "Host terminated unexpectedly!"); - return 1; - } - finally + try + { + Log.Information("Starting web host."); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + builder.Services.AddApplication(options => { - Log.CloseAndFlush(); - } + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + app.InitializeApplication(); + app.Run(); + return 0; + } + catch (Exception ex) + { + Log.Fatal(ex, "Host terminated unexpectedly!"); + return 1; + } + finally + { + Log.CloseAndFlush(); } } } From 458dc0dcc8997b79ec1278d6e073d82b2f375834 Mon Sep 17 00:00:00 2001 From: maliming Date: Tue, 14 Dec 2021 10:56:16 +0800 Subject: [PATCH 03/13] Update MyProjectNameMenuContributor.cs --- .../Menus/MyProjectNameMenuContributor.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Menus/MyProjectNameMenuContributor.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Menus/MyProjectNameMenuContributor.cs index 961cd445198..fd918a71db2 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Menus/MyProjectNameMenuContributor.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Menus/MyProjectNameMenuContributor.cs @@ -60,6 +60,9 @@ private Task ConfigureMainMenuAsync(MenuConfigurationContext context) administration.TryRemoveMenuItem(TenantManagementMenuNames.GroupName); } + administration.SetSubItemOrder(IdentityMenuNames.GroupName, 2); + administration.SetSubItemOrder(SettingManagementMenuNames.GroupName, 3); + return Task.CompletedTask; } From 8c5e3cd30aeb34eff42a3c292a9f1a4d4b19355e Mon Sep 17 00:00:00 2001 From: maliming Date: Fri, 17 Dec 2021 21:39:19 +0800 Subject: [PATCH 04/13] Async configure and initialize the module. --- .../AbpApplicationBuilderExtensions.cs | 22 ++++ .../ServiceCollectionApplicationExtensions.cs | 17 +++ .../Volo/Abp/AbpApplicationBase.cs | 107 +++++++++++++++++- .../Volo/Abp/AbpApplicationCreationOptions.cs | 3 + .../Volo/Abp/AbpApplicationFactory.cs | 55 +++++++++ ...pApplicationWithExternalServiceProvider.cs | 10 ++ ...pApplicationWithInternalServiceProvider.cs | 7 ++ .../Volo.Abp.Core/Volo/Abp/IAbpApplication.cs | 6 + ...pApplicationWithExternalServiceProvider.cs | 13 +++ ...pApplicationWithInternalServiceProvider.cs | 13 +++ .../Volo/Abp/IOnApplicationInitialization.cs | 5 +- .../Volo/Abp/IOnApplicationShutdown.cs | 5 +- .../Volo/Abp/Modularity/AbpModule.cs | 43 +++++++ .../DefaultModuleLifecycleContributor.cs | 36 +++++- .../Volo/Abp/Modularity/IAbpModule.cs | 6 +- .../Modularity/IModuleLifecycleContributor.cs | 7 +- .../Volo/Abp/Modularity/IModuleManager.cs | 7 +- .../IOnPostApplicationInitialization.cs | 5 +- .../IOnPreApplicationInitialization.cs | 5 +- .../Abp/Modularity/IPostConfigureServices.cs | 4 +- .../Abp/Modularity/IPreConfigureServices.cs | 4 +- .../ModuleLifecycleContributorBase.cs | 14 ++- .../Volo/Abp/Modularity/ModuleManager.cs | 41 +++++++ .../Abp/AbpApplication_Initialize_Tests.cs | 82 +++++++++++++- .../ConfigurationAccessor_Tests.cs | 36 +++++- .../AutoServiceRegistration_Tests.cs | 15 +++ .../HybridServiceScopeFactory_Tests.cs | 31 +++++ .../Volo/Abp/Modularity/TestModuleBase.cs | 68 ++++++++++- 28 files changed, 647 insertions(+), 20 deletions(-) diff --git a/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs index 2e8b221b3cd..b15167fa1df 100644 --- a/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.AspNetCore.RequestLocalization; using Microsoft.Extensions.DependencyInjection; @@ -18,6 +19,27 @@ public static class AbpApplicationBuilderExtensions { private const string ExceptionHandlingMiddlewareMarker = "_AbpExceptionHandlingMiddleware_Added"; + public async static Task InitializeApplicationAsync([NotNull] this IApplicationBuilder app) + { + Check.NotNull(app, nameof(app)); + + app.ApplicationServices.GetRequiredService>().Value = app; + var application = app.ApplicationServices.GetRequiredService(); + var applicationLifetime = app.ApplicationServices.GetRequiredService(); + + applicationLifetime.ApplicationStopping.Register(() => + { + application.ShutdownAsync(); + }); + + applicationLifetime.ApplicationStopped.Register(() => + { + application.Dispose(); + }); + + await application.InitializeAsync(app.ApplicationServices); + } + public static void InitializeApplication([NotNull] this IApplicationBuilder app) { Check.NotNull(app, nameof(app)); diff --git a/framework/src/Volo.Abp.Core/Microsoft/Extensions/DependencyInjection/ServiceCollectionApplicationExtensions.cs b/framework/src/Volo.Abp.Core/Microsoft/Extensions/DependencyInjection/ServiceCollectionApplicationExtensions.cs index 7748953cc42..ce4af2befae 100644 --- a/framework/src/Volo.Abp.Core/Microsoft/Extensions/DependencyInjection/ServiceCollectionApplicationExtensions.cs +++ b/framework/src/Volo.Abp.Core/Microsoft/Extensions/DependencyInjection/ServiceCollectionApplicationExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Volo.Abp; using Volo.Abp.Modularity; @@ -22,4 +23,20 @@ public static IAbpApplicationWithExternalServiceProvider AddApplication( { return AbpApplicationFactory.Create(startupModuleType, services, optionsAction); } + + public async static Task AddApplicationAsync( + [NotNull] this IServiceCollection services, + [CanBeNull] Action optionsAction = null) + where TStartupModule : IAbpModule + { + return await AbpApplicationFactory.CreateAsync(services, optionsAction); + } + + public async static Task AddApplicationAsync( + [NotNull] this IServiceCollection services, + [NotNull] Type startupModuleType, + [CanBeNull] Action optionsAction = null) + { + return await AbpApplicationFactory.CreateAsync(startupModuleType, services, optionsAction); + } } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs index 85b19894456..c6e86b4af86 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -46,7 +47,21 @@ internal AbpApplicationBase( services.AddCoreAbpServices(this, options); Modules = LoadModules(services, options); - ConfigureServices(); + + if (!options.ManualConfigureServices) + { + ConfigureServices(); + } + } + + public virtual async Task ShutdownAsync() + { + using (var scope = ServiceProvider.CreateScope()) + { + await scope.ServiceProvider + .GetRequiredService() + .ShutdownModulesAsync(new ApplicationShutdownContext(scope.ServiceProvider)); + } } public virtual void Shutdown() @@ -70,6 +85,17 @@ protected virtual void SetServiceProvider(IServiceProvider serviceProvider) ServiceProvider.GetRequiredService>().Value = ServiceProvider; } + protected virtual async Task InitializeModulesAsync() + { + using (var scope = ServiceProvider.CreateScope()) + { + WriteInitLogs(scope.ServiceProvider); + await scope.ServiceProvider + .GetRequiredService() + .InitializeModulesAsync(new ApplicationInitializationContext(scope.ServiceProvider)); + } + } + protected virtual void InitializeModules() { using (var scope = ServiceProvider.CreateScope()) @@ -111,7 +137,84 @@ protected virtual IReadOnlyList LoadModules(IServiceCollec } //TODO: We can extract a new class for this - protected virtual void ConfigureServices() + public virtual async Task ConfigureServicesAsync() + { + var context = new ServiceConfigurationContext(Services); + Services.AddSingleton(context); + + foreach (var module in Modules) + { + if (module.Instance is AbpModule abpModule) + { + abpModule.ServiceConfigurationContext = context; + } + } + + //PreConfigureServices + foreach (var module in Modules.Where(m => m.Instance is IPreConfigureServices)) + { + try + { + await ((IPreConfigureServices)module.Instance).PreConfigureServicesAsync(context); + } + catch (Exception ex) + { + throw new AbpInitializationException($"An error occurred during {nameof(IPreConfigureServices.PreConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex); + } + } + + var assemblies = new HashSet(); + + //ConfigureServices + foreach (var module in Modules) + { + if (module.Instance is AbpModule abpModule) + { + if (!abpModule.SkipAutoServiceRegistration) + { + var assembly = module.Type.Assembly; + if (!assemblies.Contains(assembly)) + { + Services.AddAssembly(assembly); + assemblies.Add(assembly); + } + } + } + + try + { + await module.Instance.ConfigureServicesAsync(context); + } + catch (Exception ex) + { + throw new AbpInitializationException($"An error occurred during {nameof(IAbpModule.ConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex); + } + } + + //PostConfigureServices + foreach (var module in Modules.Where(m => m.Instance is IPostConfigureServices)) + { + try + { + await ((IPostConfigureServices)module.Instance).PostConfigureServicesAsync(context); + } + catch (Exception ex) + { + throw new AbpInitializationException($"An error occurred during {nameof(IPostConfigureServices.PostConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex); + } + } + + foreach (var module in Modules) + { + if (module.Instance is AbpModule abpModule) + { + abpModule.ServiceConfigurationContext = null; + } + } + } + + //TODO: We can extract a new class for this + public virtual void ConfigureServices() { var context = new ServiceConfigurationContext(Services); Services.AddSingleton(context); diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs index ea2d69aae60..8bf75798433 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs @@ -19,10 +19,13 @@ public class AbpApplicationCreationOptions [NotNull] public AbpConfigurationBuilderOptions Configuration { get; } + public bool ManualConfigureServices { get; set; } + public AbpApplicationCreationOptions([NotNull] IServiceCollection services) { Services = Check.NotNull(services, nameof(services)); PlugInSources = new PlugInSourceList(); Configuration = new AbpConfigurationBuilderOptions(); + ManualConfigureServices = false; } } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs index 13b886f1c3a..d904c24ca27 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; @@ -7,6 +8,60 @@ namespace Volo.Abp; public static class AbpApplicationFactory { + public async static Task CreateAsync( + [CanBeNull] Action optionsAction = null) + where TStartupModule : IAbpModule + { + var app = Create(typeof(TStartupModule), options => + { + optionsAction?.Invoke(options); + options.ManualConfigureServices = true; + }); + await app.ConfigureServicesAsync(); + return app; + } + + public async static Task CreateAsync( + [NotNull] Type startupModuleType, + [CanBeNull] Action optionsAction = null) + { + var app = new AbpApplicationWithInternalServiceProvider(startupModuleType, options => + { + optionsAction?.Invoke(options); + options.ManualConfigureServices = true; + }); + await app.ConfigureServicesAsync(); + return app; + } + + public async static Task CreateAsync( + [NotNull] IServiceCollection services, + [CanBeNull] Action optionsAction = null) + where TStartupModule : IAbpModule + { + var app = Create(typeof(TStartupModule), services, options => + { + optionsAction?.Invoke(options); + options.ManualConfigureServices = true; + }); + await app.ConfigureServicesAsync(); + return app; + } + + public async static Task CreateAsync( + [NotNull] Type startupModuleType, + [NotNull] IServiceCollection services, + [CanBeNull] Action optionsAction = null) + { + var app = new AbpApplicationWithExternalServiceProvider(startupModuleType, services, options => + { + optionsAction?.Invoke(options); + options.ManualConfigureServices = true; + }); + await app.ConfigureServicesAsync(); + return app; + } + public static IAbpApplicationWithInternalServiceProvider Create( [CanBeNull] Action optionsAction = null) where TStartupModule : IAbpModule diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithExternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithExternalServiceProvider.cs index 162d68b5d7b..fbb9d611cf0 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithExternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithExternalServiceProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; @@ -35,6 +36,15 @@ void IAbpApplicationWithExternalServiceProvider.SetServiceProvider([NotNull] ISe SetServiceProvider(serviceProvider); } + public async Task InitializeAsync(IServiceProvider serviceProvider) + { + Check.NotNull(serviceProvider, nameof(serviceProvider)); + + SetServiceProvider(serviceProvider); + + await InitializeModulesAsync(); + } + public void Initialize([NotNull] IServiceProvider serviceProvider) { Check.NotNull(serviceProvider, nameof(serviceProvider)); diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithInternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithInternalServiceProvider.cs index eb118410cdb..245ce6fb06e 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithInternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithInternalServiceProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; @@ -44,6 +45,12 @@ public IServiceProvider CreateServiceProvider() return ServiceProvider; } + public async Task InitializeAsync() + { + CreateServiceProvider(); + await InitializeModulesAsync(); + } + public void Initialize() { CreateServiceProvider(); diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs index de9201bebce..b51fd7ec37b 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; @@ -23,6 +24,11 @@ public interface IAbpApplication : IModuleContainer, IDisposable /// IServiceProvider ServiceProvider { get; } + /// + /// Used to gracefully shutdown the application and all modules. + /// + Task ShutdownAsync(); + /// /// Used to gracefully shutdown the application and all modules. /// diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs index 91c95f45181..b4363e1161a 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; namespace Volo.Abp; @@ -10,6 +11,18 @@ public interface IAbpApplicationWithExternalServiceProvider : IAbpApplication /// void SetServiceProvider([NotNull] IServiceProvider serviceProvider); + /// + /// Call the Pre/Post/ConfigureServicesAsync method of the modules. + /// + Task ConfigureServicesAsync(); + + /// + /// Sets the service provider and initializes all the modules. + /// If was called before, the same + /// instance should be passed to this method. + /// + Task InitializeAsync([NotNull] IServiceProvider serviceProvider); + /// /// Sets the service provider and initializes all the modules. /// If was called before, the same diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs index 61fdb0652f2..8a3b4c7ca1d 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; namespace Volo.Abp; @@ -10,6 +11,18 @@ public interface IAbpApplicationWithInternalServiceProvider : IAbpApplication /// IServiceProvider CreateServiceProvider(); + /// + /// Call the Pre/Post/ConfigureServicesAsync method of the modules. + /// + Task ConfigureServicesAsync(); + + /// + /// Creates the service provider and initializes all the modules. + /// If method was called before, + /// it does not re-create it, but uses the previous one. + /// + Task InitializeAsync(); + /// /// Creates the service provider and initializes all the modules. /// If method was called before, diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationInitialization.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationInitialization.cs index 5ed95a545ba..6131a8b7104 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationInitialization.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationInitialization.cs @@ -1,8 +1,11 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp; public interface IOnApplicationInitialization { + Task OnApplicationInitializationAsync([NotNull] ApplicationInitializationContext context); + void OnApplicationInitialization([NotNull] ApplicationInitializationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationShutdown.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationShutdown.cs index ced040851ed..9f67ebb4668 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationShutdown.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationShutdown.cs @@ -1,8 +1,11 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp; public interface IOnApplicationShutdown { + Task OnApplicationShutdownAsync([NotNull] ApplicationShutdownContext context); + void OnApplicationShutdown([NotNull] ApplicationShutdownContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/AbpModule.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/AbpModule.cs index 537ccc54f6c..ae2bec31128 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/AbpModule.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/AbpModule.cs @@ -1,5 +1,6 @@ using System; using System.Reflection; +using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -30,36 +31,78 @@ protected internal ServiceConfigurationContext ServiceConfigurationContext { private ServiceConfigurationContext _serviceConfigurationContext; + public virtual Task PreConfigureServicesAsync(ServiceConfigurationContext context) + { + PreConfigureServices(context); + return Task.CompletedTask; + } + public virtual void PreConfigureServices(ServiceConfigurationContext context) { } + public virtual Task ConfigureServicesAsync(ServiceConfigurationContext context) + { + ConfigureServices(context); + return Task.CompletedTask; + } + public virtual void ConfigureServices(ServiceConfigurationContext context) { } + public virtual Task PostConfigureServicesAsync(ServiceConfigurationContext context) + { + PostConfigureServices(context); + return Task.CompletedTask; + } + public virtual void PostConfigureServices(ServiceConfigurationContext context) { } + public virtual Task OnPreApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnPreApplicationInitialization(context); + return Task.CompletedTask; + } + public virtual void OnPreApplicationInitialization(ApplicationInitializationContext context) { } + public virtual Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnApplicationInitialization(context); + return Task.CompletedTask; + } + public virtual void OnApplicationInitialization(ApplicationInitializationContext context) { } + public virtual Task OnPostApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnPostApplicationInitialization(context); + return Task.CompletedTask; + } + public virtual void OnPostApplicationInitialization(ApplicationInitializationContext context) { } + public virtual Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + OnApplicationShutdown(context); + return Task.CompletedTask; + } + public virtual void OnApplicationShutdown(ApplicationShutdownContext context) { diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/DefaultModuleLifecycleContributor.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/DefaultModuleLifecycleContributor.cs index f548cfaafbb..c520cc8d581 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/DefaultModuleLifecycleContributor.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/DefaultModuleLifecycleContributor.cs @@ -1,7 +1,17 @@ -namespace Volo.Abp.Modularity; +using System.Threading.Tasks; + +namespace Volo.Abp.Modularity; public class OnApplicationInitializationModuleLifecycleContributor : ModuleLifecycleContributorBase { + public async override Task InitializeAsync(ApplicationInitializationContext context, IAbpModule module) + { + if (module is IOnApplicationInitialization onApplicationInitialization) + { + await onApplicationInitialization.OnApplicationInitializationAsync(context); + } + } + public override void Initialize(ApplicationInitializationContext context, IAbpModule module) { (module as IOnApplicationInitialization)?.OnApplicationInitialization(context); @@ -10,6 +20,14 @@ public override void Initialize(ApplicationInitializationContext context, IAbpMo public class OnApplicationShutdownModuleLifecycleContributor : ModuleLifecycleContributorBase { + public async override Task ShutdownAsync(ApplicationShutdownContext context, IAbpModule module) + { + if (module is IOnApplicationShutdown onApplicationShutdown) + { + await onApplicationShutdown.OnApplicationShutdownAsync(context); + } + } + public override void Shutdown(ApplicationShutdownContext context, IAbpModule module) { (module as IOnApplicationShutdown)?.OnApplicationShutdown(context); @@ -18,6 +36,14 @@ public override void Shutdown(ApplicationShutdownContext context, IAbpModule mod public class OnPreApplicationInitializationModuleLifecycleContributor : ModuleLifecycleContributorBase { + public async override Task InitializeAsync(ApplicationInitializationContext context, IAbpModule module) + { + if (module is IOnPreApplicationInitialization onPreApplicationInitialization) + { + await onPreApplicationInitialization.OnPreApplicationInitializationAsync(context); + } + } + public override void Initialize(ApplicationInitializationContext context, IAbpModule module) { (module as IOnPreApplicationInitialization)?.OnPreApplicationInitialization(context); @@ -26,6 +52,14 @@ public override void Initialize(ApplicationInitializationContext context, IAbpMo public class OnPostApplicationInitializationModuleLifecycleContributor : ModuleLifecycleContributorBase { + public async override Task InitializeAsync(ApplicationInitializationContext context, IAbpModule module) + { + if (module is IOnPostApplicationInitialization onPostApplicationInitialization) + { + await onPostApplicationInitialization.OnPostApplicationInitializationAsync(context); + } + } + public override void Initialize(ApplicationInitializationContext context, IAbpModule module) { (module as IOnPostApplicationInitialization)?.OnPostApplicationInitialization(context); diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IAbpModule.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IAbpModule.cs index b992020d4c0..3622a503241 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IAbpModule.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IAbpModule.cs @@ -1,6 +1,10 @@ -namespace Volo.Abp.Modularity; +using System.Threading.Tasks; + +namespace Volo.Abp.Modularity; public interface IAbpModule { + Task ConfigureServicesAsync(ServiceConfigurationContext context); + void ConfigureServices(ServiceConfigurationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleLifecycleContributor.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleLifecycleContributor.cs index 299bfe9e5a0..ca0ad1cfd81 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleLifecycleContributor.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleLifecycleContributor.cs @@ -1,11 +1,16 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; using Volo.Abp.DependencyInjection; namespace Volo.Abp.Modularity; public interface IModuleLifecycleContributor : ITransientDependency { + Task InitializeAsync([NotNull] ApplicationInitializationContext context, [NotNull] IAbpModule module); + void Initialize([NotNull] ApplicationInitializationContext context, [NotNull] IAbpModule module); + Task ShutdownAsync([NotNull] ApplicationShutdownContext context, [NotNull] IAbpModule module); + void Shutdown([NotNull] ApplicationShutdownContext context, [NotNull] IAbpModule module); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleManager.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleManager.cs index d981b745b9b..eb4cf52e3c6 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleManager.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleManager.cs @@ -1,10 +1,15 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp.Modularity; public interface IModuleManager { + Task InitializeModulesAsync([NotNull] ApplicationInitializationContext context); + void InitializeModules([NotNull] ApplicationInitializationContext context); + Task ShutdownModulesAsync([NotNull] ApplicationShutdownContext context); + void ShutdownModules([NotNull] ApplicationShutdownContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPostApplicationInitialization.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPostApplicationInitialization.cs index d79a0318ec7..26177360f97 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPostApplicationInitialization.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPostApplicationInitialization.cs @@ -1,8 +1,11 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp.Modularity; public interface IOnPostApplicationInitialization { + Task OnPostApplicationInitializationAsync([NotNull] ApplicationInitializationContext context); + void OnPostApplicationInitialization([NotNull] ApplicationInitializationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPreApplicationInitialization.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPreApplicationInitialization.cs index 0426ef50af5..7e63301e3e2 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPreApplicationInitialization.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPreApplicationInitialization.cs @@ -1,8 +1,11 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp.Modularity; public interface IOnPreApplicationInitialization { + Task OnPreApplicationInitializationAsync([NotNull] ApplicationInitializationContext context); + void OnPreApplicationInitialization([NotNull] ApplicationInitializationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPostConfigureServices.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPostConfigureServices.cs index 38d3449b856..a1ea07de275 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPostConfigureServices.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPostConfigureServices.cs @@ -1,8 +1,10 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; namespace Volo.Abp.Modularity; public interface IPostConfigureServices { + Task PostConfigureServicesAsync(ServiceConfigurationContext context); + void PostConfigureServices(ServiceConfigurationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPreConfigureServices.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPreConfigureServices.cs index 51db8f5fb8e..dfb9eef1dfe 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPreConfigureServices.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPreConfigureServices.cs @@ -1,8 +1,10 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; namespace Volo.Abp.Modularity; public interface IPreConfigureServices { + Task PreConfigureServicesAsync(ServiceConfigurationContext context); + void PreConfigureServices(ServiceConfigurationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleLifecycleContributorBase.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleLifecycleContributorBase.cs index b3ac566eabc..3192d1f2eac 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleLifecycleContributorBase.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleLifecycleContributorBase.cs @@ -1,11 +1,23 @@ -namespace Volo.Abp.Modularity; +using System.Threading.Tasks; + +namespace Volo.Abp.Modularity; public abstract class ModuleLifecycleContributorBase : IModuleLifecycleContributor { + public virtual Task InitializeAsync(ApplicationInitializationContext context, IAbpModule module) + { + return Task.CompletedTask; + } + public virtual void Initialize(ApplicationInitializationContext context, IAbpModule module) { } + public virtual Task ShutdownAsync(ApplicationShutdownContext context, IAbpModule module) + { + return Task.CompletedTask; + } + public virtual void Shutdown(ApplicationShutdownContext context, IAbpModule module) { } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleManager.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleManager.cs index 2218b2f6fd8..71697a1a831 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleManager.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -30,6 +31,26 @@ public ModuleManager( .ToArray(); } + public virtual async Task InitializeModulesAsync(ApplicationInitializationContext context) + { + foreach (var contributor in _lifecycleContributors) + { + foreach (var module in _moduleContainer.Modules) + { + try + { + await contributor.InitializeAsync(context, module.Instance); + } + catch (Exception ex) + { + throw new AbpInitializationException($"An error occurred during the initialize {contributor.GetType().FullName} phase of the module {module.Type.AssemblyQualifiedName}: {ex.Message}. See the inner exception for details.", ex); + } + } + } + + _logger.LogInformation("Initialized all ABP modules."); + } + public void InitializeModules(ApplicationInitializationContext context) { foreach (var contributor in _lifecycleContributors) @@ -50,6 +71,26 @@ public void InitializeModules(ApplicationInitializationContext context) _logger.LogInformation("Initialized all ABP modules."); } + public virtual async Task ShutdownModulesAsync(ApplicationShutdownContext context) + { + var modules = _moduleContainer.Modules.Reverse().ToList(); + + foreach (var contributor in _lifecycleContributors) + { + foreach (var module in modules) + { + try + { + await contributor.ShutdownAsync(context, module.Instance); + } + catch (Exception ex) + { + throw new AbpShutdownException($"An error occurred during the shutdown {contributor.GetType().FullName} phase of the module {module.Type.AssemblyQualifiedName}: {ex.Message}. See the inner exception for details.", ex); + } + } + } + } + public void ShutdownModules(ApplicationShutdownContext context) { var modules = _moduleContainer.Modules.Reverse().ToList(); diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/AbpApplication_Initialize_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/AbpApplication_Initialize_Tests.cs index 63bc7f5f78d..f69d94ce61d 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/AbpApplication_Initialize_Tests.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/AbpApplication_Initialize_Tests.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Modularity; using Volo.Abp.Modularity.PlugIns; @@ -8,6 +9,39 @@ namespace Volo.Abp; public class AbpApplication_Initialize_Tests { + [Fact] + public async Task Should_Initialize_Single_Module_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + //Assert + var module = application.Services.GetSingletonInstance(); + + module.PreConfigureServicesAsyncIsCalled.ShouldBeTrue(); + module.PreConfigureServicesIsCalled.ShouldBeTrue(); + + module.ConfigureServicesAsyncIsCalled.ShouldBeTrue(); + module.ConfigureServicesIsCalled.ShouldBeTrue(); + + module.PostConfigureServicesAsyncIsCalled.ShouldBeTrue(); + module.PostConfigureServicesIsCalled.ShouldBeTrue(); + + //Act + await application.InitializeAsync(); + + //Assert + application.ServiceProvider.GetRequiredService().ShouldBeSameAs(module); + module.OnApplicationInitializeAsyncIsCalled.ShouldBeTrue(); + module.OnApplicationInitializeIsCalled.ShouldBeTrue(); + //Act + await application.ShutdownAsync(); + + //Assert + module.OnApplicationShutdownAsyncIsCalled.ShouldBeTrue(); + module.OnApplicationShutdownIsCalled.ShouldBeTrue(); + } + } + [Fact] public void Should_Initialize_Single_Module() { @@ -34,6 +68,50 @@ public void Should_Initialize_Single_Module() } } + [Fact] + public async Task Should_Initialize_PlugIn_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync(options => + { + options.PlugInSources.AddTypes(typeof(IndependentEmptyPlugInModule)); + })) + { + //Assert + var plugInModule = application.Services.GetSingletonInstance(); + + plugInModule.PreConfigureServicesAsyncIsCalled.ShouldBeTrue(); + plugInModule.PreConfigureServicesIsCalled.ShouldBeTrue(); + + plugInModule.ConfigureServicesAsyncIsCalled.ShouldBeTrue(); + plugInModule.ConfigureServicesIsCalled.ShouldBeTrue(); + + plugInModule.PostConfigureServicesAsyncIsCalled.ShouldBeTrue(); + plugInModule.PostConfigureServicesIsCalled.ShouldBeTrue(); + + //Act + await application.InitializeAsync(); + + //Assert + application.ServiceProvider.GetRequiredService().ShouldBeSameAs(plugInModule); + + plugInModule.OnPreApplicationInitializationAsyncIsCalled.ShouldBeTrue(); + plugInModule.OnPreApplicationInitializationIsCalled.ShouldBeTrue(); + + plugInModule.OnApplicationInitializeAsyncIsCalled.ShouldBeTrue(); + plugInModule.OnApplicationInitializeIsCalled.ShouldBeTrue(); + + plugInModule.OnPostApplicationInitializationAsyncIsCalled.ShouldBeTrue(); + plugInModule.OnPostApplicationInitializationIsCalled.ShouldBeTrue(); + + //Act + await application.ShutdownAsync(); + + //Assert + plugInModule.OnApplicationShutdownAsyncIsCalled.ShouldBeTrue(); + plugInModule.OnApplicationShutdownIsCalled.ShouldBeTrue(); + } + } + [Fact] public void Should_Initialize_PlugIn() { @@ -53,7 +131,9 @@ public void Should_Initialize_PlugIn() //Assert application.ServiceProvider.GetRequiredService().ShouldBeSameAs(plugInModule); + plugInModule.OnPreApplicationInitializationIsCalled.ShouldBeTrue(); plugInModule.OnApplicationInitializeIsCalled.ShouldBeTrue(); + plugInModule.OnPostApplicationInitializationIsCalled.ShouldBeTrue(); //Act application.Shutdown(); diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Configuration/ConfigurationAccessor_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Configuration/ConfigurationAccessor_Tests.cs index 9023fb6ce7b..4a0dda26fb2 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Configuration/ConfigurationAccessor_Tests.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Configuration/ConfigurationAccessor_Tests.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Modularity; @@ -8,6 +9,22 @@ namespace Volo.Abp.Configuration; public class ConfigurationAccessor_Tests { + [Fact] + public async Task Should_Use_Empty_ConfigurationRoot_By_Default_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + var configuration1 = application.Services.GetConfiguration(); + configuration1.ShouldNotBeNull(); + + await application.InitializeAsync(); + + var configuration2 = ResolveConfiguration(application); + + configuration2.ShouldBe(configuration1); + } + } + [Fact] public void Should_Use_Empty_ConfigurationRoot_By_Default() { @@ -24,6 +41,23 @@ public void Should_Use_Empty_ConfigurationRoot_By_Default() } } + [Fact] + public async Task Should_Use_The_Registered_ConfigurationRoot_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + var myConfiguration = new ConfigurationBuilder().Build(); + application.Services.ReplaceConfiguration(myConfiguration); + application.Services.GetConfiguration().ShouldBe(myConfiguration); + + await application.InitializeAsync(); + + var configuration = ResolveConfiguration(application); + + configuration.ShouldBe(myConfiguration); + } + } + [Fact] public void Should_Use_The_Registered_ConfigurationRoot() { diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/AutoServiceRegistration_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/AutoServiceRegistration_Tests.cs index 6fc5716a22c..71ec5598248 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/AutoServiceRegistration_Tests.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/AutoServiceRegistration_Tests.cs @@ -1,4 +1,5 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Modularity; @@ -8,6 +9,20 @@ namespace Volo.Abp.DependencyInjection; public class AutoServiceRegistration_Tests { + [Fact] + public async Task AutoServiceRegistration_Should_Not_Duplicate_Test_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + //Act + await application.InitializeAsync(); + + //Assert + var services = application.ServiceProvider.GetServices().ToList(); + services.Count.ShouldBe(1); + } + } + [Fact] public void AutoServiceRegistration_Should_Not_Duplicate_Test() { diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/HybridServiceScopeFactory_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/HybridServiceScopeFactory_Tests.cs index d665c863dc8..6a3f059ba83 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/HybridServiceScopeFactory_Tests.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/HybridServiceScopeFactory_Tests.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Modularity; @@ -8,6 +9,26 @@ namespace Volo.Abp.DependencyInjection; public class HybridServiceScopeFactory_Tests { + [Fact] + public async Task Should_Use_Default_ServiceScopeFactory_By_Default_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + application.Services.AddType(typeof(MyServiceAsync)); + + await application.InitializeAsync(); + + var serviceScopeFactory = application.ServiceProvider.GetRequiredService(); + + using (var scope = serviceScopeFactory.CreateScope()) + { + scope.ServiceProvider.GetRequiredService(); + } + + MyServiceAsync.DisposeCount.ShouldBe(1); + } + } + [Fact] public void Should_Use_Default_ServiceScopeFactory_By_Default() { @@ -28,6 +49,16 @@ public void Should_Use_Default_ServiceScopeFactory_By_Default() } } + private class MyServiceAsync : ITransientDependency, IDisposable + { + public static int DisposeCount { get; private set; } + + public void Dispose() + { + ++DisposeCount; + } + } + private class MyService : ITransientDependency, IDisposable { public static int DisposeCount { get; private set; } diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Modularity/TestModuleBase.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Modularity/TestModuleBase.cs index 327d2982a52..29b7927c640 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Modularity/TestModuleBase.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Modularity/TestModuleBase.cs @@ -1,39 +1,97 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; namespace Volo.Abp.Modularity; public class TestModuleBase : AbpModule { - public bool PreConfigureServicesIsCalled { get; set; } + public bool PreConfigureServicesAsyncIsCalled { get; set; } + public bool ConfigureServicesAsyncIsCalled { get; set; } + public bool PostConfigureServicesAsyncIsCalled { get; set; } + public bool OnPreApplicationInitializationIsCalled { get; set; } + public bool OnPostApplicationInitializationIsCalled { get; set; } + public bool OnApplicationInitializeAsyncIsCalled { get; set; } + public bool OnApplicationShutdownAsyncIsCalled { get; set; } + public bool PreConfigureServicesIsCalled { get; set; } public bool ConfigureServicesIsCalled { get; set; } - public bool PostConfigureServicesIsCalled { get; set; } - + public bool OnPreApplicationInitializationAsyncIsCalled { get; set; } + public bool OnPostApplicationInitializationAsyncIsCalled { get; set; } public bool OnApplicationInitializeIsCalled { get; set; } - public bool OnApplicationShutdownIsCalled { get; set; } + public override Task PreConfigureServicesAsync(ServiceConfigurationContext context) + { + PreConfigureServicesAsyncIsCalled = true; + return base.PreConfigureServicesAsync(context); + } + public override void PreConfigureServices(ServiceConfigurationContext context) { PreConfigureServicesIsCalled = true; } + public override Task ConfigureServicesAsync(ServiceConfigurationContext context) + { + ConfigureServicesAsyncIsCalled = true; + return base.ConfigureServicesAsync(context); + } + public override void ConfigureServices(ServiceConfigurationContext context) { ConfigureServicesIsCalled = true; } + public override Task PostConfigureServicesAsync(ServiceConfigurationContext context) + { + PostConfigureServicesAsyncIsCalled = true; + return base.PostConfigureServicesAsync(context); + } + public override void PostConfigureServices(ServiceConfigurationContext context) { PostConfigureServicesIsCalled = true; } + public override Task OnPreApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnPreApplicationInitializationAsyncIsCalled = true; + return base.OnPreApplicationInitializationAsync(context); + } + + public override void OnPreApplicationInitialization(ApplicationInitializationContext context) + { + OnPreApplicationInitializationIsCalled = true; + } + + public override Task OnPostApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnPostApplicationInitializationAsyncIsCalled = true; + return base.OnPostApplicationInitializationAsync(context); + } + + public override void OnPostApplicationInitialization(ApplicationInitializationContext context) + { + OnPostApplicationInitializationIsCalled = true; + } + + public override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnApplicationInitializeAsyncIsCalled = true; + return base.OnApplicationInitializationAsync(context); + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { OnApplicationInitializeIsCalled = true; } + public override Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + OnApplicationShutdownAsyncIsCalled = true; + return base.OnApplicationShutdownAsync(context); + } + public override void OnApplicationShutdown(ApplicationShutdownContext context) { OnApplicationShutdownIsCalled = true; From 2212157f03c0fc1bbc99882052d1c732df277e5f Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 20 Dec 2021 17:59:53 +0800 Subject: [PATCH 05/13] Refactor. --- .../AbpAspNetCoreAsyncIntegratedTestBase.cs | 118 ++++++++++++++++++ .../TestBase/TestNoopHostLifetime.cs | 18 +++ .../AbpBackgroundJobsRabbitMqModule.cs | 37 +++--- .../BackgroundJobs/AbpBackgroundJobsModule.cs | 15 ++- .../HangfireBackgroundWorkerManager.cs | 2 +- .../AbpBackgroundWorkersQuartzModule.cs | 18 ++- .../Quartz/QuartzBackgroundWorkerManager.cs | 4 +- .../AbpBackgroundWorkersModule.cs | 25 +++- .../BackgroundWorkerManager.cs | 6 +- ...licationInitializationContextExtensions.cs | 11 +- .../IBackgroundWorkerManager.cs | 5 +- .../Volo/Abp/EventBus/AbpEventBusModule.cs | 12 +- .../Volo/Abp/Quartz/AbpQuartzModule.cs | 25 +++- .../Mvc/AbpAspNetCoreAsyncTestBase_Tests.cs | 62 +++++++++ .../AspNetCore/AbpAspNetCoreAsyncTestBase.cs | 45 +++++++ .../Volo/Docs/DocsDomainModule.cs | 15 ++- .../AbpIdentityServerDomainModule.cs | 23 +++- .../Program.cs | 9 +- .../Program.cs | 9 +- .../Program.cs | 2 +- .../Program.cs | 9 +- .../Program.cs | 9 +- .../Program.cs | 9 +- .../Program.cs | 9 +- .../Program.cs | 9 +- .../Program.cs | 2 +- .../MyProjectNameBlazorHostModule.cs | 12 +- .../Program.cs | 40 +++--- .../Startup.cs | 18 --- .../Program.cs | 41 +++--- .../Startup.cs | 20 --- .../MyProjectNameIdentityServerModule.cs | 20 ++- .../Program.cs | 41 +++--- .../Startup.cs | 20 --- .../Program.cs | 38 +++--- .../Startup.cs | 18 --- .../MyProjectNameWebUnifiedModule.cs | 12 +- .../Program.cs | 36 +++--- .../Startup.cs | 19 --- 39 files changed, 558 insertions(+), 285 deletions(-) create mode 100644 framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs create mode 100644 framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/TestNoopHostLifetime.cs create mode 100644 framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreAsyncTestBase_Tests.cs create mode 100644 framework/test/Volo.Abp.AspNetCore.Tests/Volo/Abp/AspNetCore/AbpAspNetCoreAsyncTestBase.cs delete mode 100644 templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Startup.cs delete mode 100644 templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs delete mode 100644 templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Startup.cs delete mode 100644 templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Startup.cs delete mode 100644 templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Startup.cs diff --git a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs new file mode 100644 index 00000000000..06a46897fac --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Volo.Abp.Modularity; + +namespace Volo.Abp.AspNetCore.TestBase; + +public class AbpAspNetCoreAsyncIntegratedTestBase + where TModule : AbpModule +{ + protected IHost Host { get; set; } + + protected TestServer Server { get; set; } + + protected HttpClient Client { get; set; } + + protected IServiceProvider ServiceProvider { get; set; } + + protected virtual T GetService() + { + return ServiceProvider.GetService(); + } + + protected virtual T GetRequiredService() + { + return ServiceProvider.GetRequiredService(); + } + + public virtual async Task InitializeAsync() + { + var builder = WebApplication.CreateBuilder(); + builder.Host.ConfigureServices(services => + { + services.AddSingleton(); + services.AddSingleton(); + }) + .UseAutofac(); + + await builder.Services.AddApplicationAsync(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + + await ConfigureServicesAsync(builder.Services); + + var app = builder.Build(); + + await app.InitializeApplicationAsync(); + + await app.StartAsync(); + + Host = app.Services.GetRequiredService(); + + Server = Host.GetTestServer(); + Client = Host.GetTestClient(); + + ServiceProvider = Server.Services; + + ServiceProvider.GetRequiredService().Server = Server; + } + + public virtual Task DisposeAsync() + { + return Task.CompletedTask; + } + + protected virtual Task ConfigureServicesAsync(IServiceCollection services) + { + return Task.CompletedTask; + } + + #region GetUrl + + /// + /// Gets default URL for given controller type. + /// + /// The type of the controller. + protected virtual string GetUrl() + { + return "/" + typeof(TController).Name.RemovePostFix("Controller", "AppService", "ApplicationService", "Service"); + } + + /// + /// Gets default URL for given controller type's given action. + /// + /// The type of the controller. + protected virtual string GetUrl(string actionName) + { + return GetUrl() + "/" + actionName; + } + + /// + /// Gets default URL for given controller type's given action with query string parameters (as anonymous object). + /// + /// The type of the controller. + protected virtual string GetUrl(string actionName, object queryStringParamsAsAnonymousObject) + { + var url = GetUrl(actionName); + + var dictionary = new RouteValueDictionary(queryStringParamsAsAnonymousObject); + if (dictionary.Any()) + { + url += "?" + dictionary.Select(d => $"{d.Key}={d.Value}").JoinAsString("&"); + } + + return url; + } + + #endregion +} diff --git a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/TestNoopHostLifetime.cs b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/TestNoopHostLifetime.cs new file mode 100644 index 00000000000..a0fe2d46c1e --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/TestNoopHostLifetime.cs @@ -0,0 +1,18 @@ +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; + +namespace Volo.Abp.AspNetCore.TestBase; + +public class TestNoopHostLifetime : IHostLifetime +{ + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + public Task WaitForStartAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } +} diff --git a/framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/AbpBackgroundJobsRabbitMqModule.cs b/framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/AbpBackgroundJobsRabbitMqModule.cs index 33cbc740e4e..c601ca5549e 100644 --- a/framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/AbpBackgroundJobsRabbitMqModule.cs +++ b/framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/AbpBackgroundJobsRabbitMqModule.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; using Volo.Abp.RabbitMQ; using Volo.Abp.Threading; @@ -17,31 +18,37 @@ public override void ConfigureServices(ServiceConfigurationContext context) context.Services.AddSingleton(typeof(IJobQueue<>), typeof(JobQueue<>)); } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + await StartJobQueueManagerAsync(context); + } + + public async override Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + await StopJobQueueManagerAsync(context); + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { - StartJobQueueManager(context); + AsyncHelper.RunSync(() => StartJobQueueManagerAsync(context)); } public override void OnApplicationShutdown(ApplicationShutdownContext context) { - StopJobQueueManager(context); + AsyncHelper.RunSync(() => StopJobQueueManagerAsync(context)); } - private static void StartJobQueueManager(ApplicationInitializationContext context) + private async static Task StartJobQueueManagerAsync(ApplicationInitializationContext context) { - AsyncHelper.RunSync( - () => context.ServiceProvider - .GetRequiredService() - .StartAsync() - ); + await context.ServiceProvider + .GetRequiredService() + .StartAsync(); } - private static void StopJobQueueManager(ApplicationShutdownContext context) + private async static Task StopJobQueueManagerAsync(ApplicationShutdownContext context) { - AsyncHelper.RunSync( - () => context.ServiceProvider - .GetRequiredService() - .StopAsync() - ); + await context.ServiceProvider + .GetRequiredService() + .StopAsync(); } } diff --git a/framework/src/Volo.Abp.BackgroundJobs/Volo/Abp/BackgroundJobs/AbpBackgroundJobsModule.cs b/framework/src/Volo.Abp.BackgroundJobs/Volo/Abp/BackgroundJobs/AbpBackgroundJobsModule.cs index aaa4a7ba011..47a165ca835 100644 --- a/framework/src/Volo.Abp.BackgroundJobs/Volo/Abp/BackgroundJobs/AbpBackgroundJobsModule.cs +++ b/framework/src/Volo.Abp.BackgroundJobs/Volo/Abp/BackgroundJobs/AbpBackgroundJobsModule.cs @@ -1,9 +1,11 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Volo.Abp.BackgroundWorkers; using Volo.Abp.DistributedLocking; using Volo.Abp.Guids; using Volo.Abp.Modularity; +using Volo.Abp.Threading; using Volo.Abp.Timing; namespace Volo.Abp.BackgroundJobs; @@ -17,12 +19,21 @@ namespace Volo.Abp.BackgroundJobs; )] public class AbpBackgroundJobsModule : AbpModule { + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + if (options.IsJobExecutionEnabled) + { + await context.AddBackgroundWorkerAsync(); + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { var options = context.ServiceProvider.GetRequiredService>().Value; if (options.IsJobExecutionEnabled) { - context.AddBackgroundWorker(); + AsyncHelper.RunSync(() => context.AddBackgroundWorkerAsync()); } } } diff --git a/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireBackgroundWorkerManager.cs index 162b2fa4722..e1525ade96b 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireBackgroundWorkerManager.cs @@ -21,7 +21,7 @@ public Task StopAsync(CancellationToken cancellationToken = default) return Task.CompletedTask; } - public void Add(IBackgroundWorker worker) + public async Task AddAsync(IBackgroundWorker worker) { if (worker is IHangfireBackgroundWorker hangfireBackgroundWorker) { diff --git a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/AbpBackgroundWorkersQuartzModule.cs b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/AbpBackgroundWorkersQuartzModule.cs index 5884532f1e9..07586b461bc 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/AbpBackgroundWorkersQuartzModule.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/AbpBackgroundWorkersQuartzModule.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Options; using Volo.Abp.Modularity; using Volo.Abp.Quartz; +using Volo.Abp.Threading; namespace Volo.Abp.BackgroundWorkers.Quartz; @@ -34,6 +35,21 @@ public override void OnPreApplicationInitialization(ApplicationInitializationCon } } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var quartzBackgroundWorkerOptions = context.ServiceProvider.GetRequiredService>().Value; + if (quartzBackgroundWorkerOptions.IsAutoRegisterEnabled) + { + var backgroundWorkerManager = context.ServiceProvider.GetRequiredService(); + var works = context.ServiceProvider.GetServices().Where(x => x.AutoRegister); + + foreach (var work in works) + { + await backgroundWorkerManager.AddAsync(work); + } + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { var quartzBackgroundWorkerOptions = context.ServiceProvider.GetRequiredService>().Value; @@ -44,7 +60,7 @@ public override void OnApplicationInitialization(ApplicationInitializationContex foreach (var work in works) { - backgroundWorkerManager.Add(work); + AsyncHelper.RunSync(() => backgroundWorkerManager.AddAsync(work)); } } } diff --git a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzBackgroundWorkerManager.cs index efee2d21399..954f21bcdad 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzBackgroundWorkerManager.cs @@ -33,9 +33,9 @@ public virtual async Task StopAsync(CancellationToken cancellationToken = defaul } } - public virtual void Add(IBackgroundWorker worker) + public virtual async Task AddAsync(IBackgroundWorker worker) { - AsyncHelper.RunSync(() => ReScheduleJobAsync(worker)); + await ReScheduleJobAsync(worker); } protected virtual async Task ReScheduleJobAsync(IBackgroundWorker worker) diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AbpBackgroundWorkersModule.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AbpBackgroundWorkersModule.cs index 40c4a70fb10..32341f101e6 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AbpBackgroundWorkersModule.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AbpBackgroundWorkersModule.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Volo.Abp.Modularity; using Volo.Abp.Threading; @@ -10,6 +11,28 @@ namespace Volo.Abp.BackgroundWorkers; )] public class AbpBackgroundWorkersModule : AbpModule { + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + if (options.IsEnabled) + { + await context.ServiceProvider + .GetRequiredService() + .StartAsync(); + } + } + + public async override Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + if (options.IsEnabled) + { + await context.ServiceProvider + .GetRequiredService() + .StopAsync(); + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { var options = context.ServiceProvider.GetRequiredService>().Value; diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerManager.cs index 62c1f3607bb..3276c837c03 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerManager.cs @@ -26,15 +26,13 @@ public BackgroundWorkerManager() _backgroundWorkers = new List(); } - public virtual void Add(IBackgroundWorker worker) + public virtual async Task AddAsync(IBackgroundWorker worker) { _backgroundWorkers.Add(worker); if (IsRunning) { - AsyncHelper.RunSync( - () => worker.StartAsync() - ); + await worker.StartAsync(); } } diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs index 5cff67b7de0..9df0f6c5e44 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; @@ -6,17 +7,17 @@ namespace Volo.Abp.BackgroundWorkers; public static class BackgroundWorkersApplicationInitializationContextExtensions { - public static ApplicationInitializationContext AddBackgroundWorker([NotNull] this ApplicationInitializationContext context) + public async static Task AddBackgroundWorkerAsync([NotNull] this ApplicationInitializationContext context) where TWorker : IBackgroundWorker { Check.NotNull(context, nameof(context)); - context.AddBackgroundWorker(typeof(TWorker)); + await context.AddBackgroundWorkerAsync(typeof(TWorker)); return context; } - public static ApplicationInitializationContext AddBackgroundWorker([NotNull] this ApplicationInitializationContext context, [NotNull] Type workerType) + public async static Task AddBackgroundWorkerAsync([NotNull] this ApplicationInitializationContext context, [NotNull] Type workerType) { Check.NotNull(context, nameof(context)); Check.NotNull(workerType, nameof(workerType)); @@ -26,9 +27,9 @@ public static ApplicationInitializationContext AddBackgroundWorker([NotNull] thi throw new AbpException($"Given type ({workerType.AssemblyQualifiedName}) must implement the {typeof(IBackgroundWorker).AssemblyQualifiedName} interface, but it doesn't!"); } - context.ServiceProvider + await context.ServiceProvider .GetRequiredService() - .Add( + .AddAsync( (IBackgroundWorker)context.ServiceProvider.GetRequiredService(workerType) ); diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IBackgroundWorkerManager.cs index e1bf0e53f27..7f5268afffe 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IBackgroundWorkerManager.cs @@ -1,4 +1,5 @@ -using Volo.Abp.Threading; +using System.Threading.Tasks; +using Volo.Abp.Threading; namespace Volo.Abp.BackgroundWorkers; @@ -13,5 +14,5 @@ public interface IBackgroundWorkerManager : IRunnable /// /// The worker. It should be resolved from IOC. /// - void Add(IBackgroundWorker worker); + Task AddAsync(IBackgroundWorker worker); } diff --git a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/AbpEventBusModule.cs b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/AbpEventBusModule.cs index cb0a32f47cb..b4a873dcd42 100644 --- a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/AbpEventBusModule.cs +++ b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/AbpEventBusModule.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; +using System.Threading.Tasks; using Volo.Abp.BackgroundWorkers; using Volo.Abp.DistributedLocking; using Volo.Abp.EventBus.Abstractions; @@ -12,6 +13,7 @@ using Volo.Abp.Modularity; using Volo.Abp.MultiTenancy; using Volo.Abp.Reflection; +using Volo.Abp.Threading; namespace Volo.Abp.EventBus; @@ -30,10 +32,16 @@ public override void PreConfigureServices(ServiceConfigurationContext context) AddEventHandlers(context.Services); } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + await context.AddBackgroundWorkerAsync(); + await context.AddBackgroundWorkerAsync(); + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { - context.AddBackgroundWorker(); - context.AddBackgroundWorker(); + AsyncHelper.RunSync(() => context.AddBackgroundWorkerAsync()); + AsyncHelper.RunSync(() => context.AddBackgroundWorkerAsync()); } private static void AddEventHandlers(IServiceCollection services) diff --git a/framework/src/Volo.Abp.Quartz/Volo/Abp/Quartz/AbpQuartzModule.cs b/framework/src/Volo.Abp.Quartz/Volo/Abp/Quartz/AbpQuartzModule.cs index ade14f1b833..db790a717d8 100644 --- a/framework/src/Volo.Abp.Quartz/Volo/Abp/Quartz/AbpQuartzModule.cs +++ b/framework/src/Volo.Abp.Quartz/Volo/Abp/Quartz/AbpQuartzModule.cs @@ -1,8 +1,8 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Quartz; using Quartz.Impl; -using Quartz.Impl.AdoJobStore.Common; using Volo.Abp.Modularity; using Volo.Abp.Threading; @@ -18,8 +18,8 @@ public override void ConfigureServices(ServiceConfigurationContext context) context.Services.AddQuartz(options.Properties, build => { - // these are the defaults - if (options.Properties[StdSchedulerFactory.PropertySchedulerJobFactoryType] == null) + // these are the defaults + if (options.Properties[StdSchedulerFactory.PropertySchedulerJobFactoryType] == null) { build.UseMicrosoftDependencyInjectionScopedJobFactory(); } @@ -62,6 +62,23 @@ public override void ConfigureServices(ServiceConfigurationContext context) }); } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + + _scheduler = context.ServiceProvider.GetRequiredService(); + + await options.StartSchedulerFactory.Invoke(_scheduler); + } + + public async override Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + if (_scheduler.IsStarted) + { + await _scheduler.Shutdown(); + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { var options = context.ServiceProvider.GetRequiredService>().Value; diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreAsyncTestBase_Tests.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreAsyncTestBase_Tests.cs new file mode 100644 index 00000000000..5d475966a27 --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreAsyncTestBase_Tests.cs @@ -0,0 +1,62 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Volo.Abp.AspNetCore.TestBase; +using Volo.Abp.Autofac; +using Volo.Abp.Modularity; +using Xunit; + +namespace Volo.Abp.AspNetCore.Mvc; + +public class AbpAspNetCoreAsyncTestBase_Tests : AbpAspNetCoreAsyncTestBase +{ + [Fact] + public async Task Get_API_Response_Test() + { + var result = await GetResponseAsStringAsync("/api"); + result.ShouldBe(await GetRequiredService().GetResponseAsync()); + } +} + +[DependsOn( + typeof(AbpAspNetCoreMvcModule), + typeof(AbpAspNetCoreTestBaseModule), + typeof(AbpAutofacModule) +)] +public class AbpAspNetCoreAsyncTestModule : AbpModule +{ + public override Task ConfigureServicesAsync(ServiceConfigurationContext context) + { + context.Services.AddTransient(); + return Task.CompletedTask; + } + + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var app = context.GetApplicationBuilder(); + + var dataBaseService = app.ApplicationServices.GetRequiredService(); + + var apiResponse = await dataBaseService.GetResponseAsync(); + app.Map("/api", _ => + { + app.Run(async httpContext => + { + await httpContext.Response.WriteAsync(apiResponse); + }); + }); + + app.UseRouting(); + app.UseConfiguredEndpoints(); + } +} + +public class DataBaseService +{ + public Task GetResponseAsync() + { + return Task.FromResult("hello api!"); + } +} diff --git a/framework/test/Volo.Abp.AspNetCore.Tests/Volo/Abp/AspNetCore/AbpAspNetCoreAsyncTestBase.cs b/framework/test/Volo.Abp.AspNetCore.Tests/Volo/Abp/AspNetCore/AbpAspNetCoreAsyncTestBase.cs new file mode 100644 index 00000000000..0d222deab46 --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Tests/Volo/Abp/AspNetCore/AbpAspNetCoreAsyncTestBase.cs @@ -0,0 +1,45 @@ +using System.Globalization; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +using Microsoft.Net.Http.Headers; +using Shouldly; +using Volo.Abp.AspNetCore.TestBase; +using Volo.Abp.Modularity; +using Xunit; + +namespace Volo.Abp.AspNetCore; + +public abstract class AbpAspNetCoreAsyncTestBase : AbpAspNetCoreAsyncIntegratedTestBase, IAsyncLifetime + where TModule : AbpModule +{ + protected virtual async Task GetResponseAsObjectAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) + { + var strResponse = await GetResponseAsStringAsync(url, expectedStatusCode); + return JsonSerializer.Deserialize(strResponse, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); + } + + protected virtual async Task GetResponseAsStringAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) + { + using (var response = await GetResponseAsync(url, expectedStatusCode)) + { + return await response.Content.ReadAsStringAsync(); + } + } + + protected virtual async Task GetResponseAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, bool xmlHttpRequest = false) + { + using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, url)) + { + requestMessage.Headers.Add("Accept-Language", CultureInfo.CurrentUICulture.Name); + if (xmlHttpRequest) + { + requestMessage.Headers.Add(HeaderNames.XRequestedWith, "XMLHttpRequest"); + } + var response = await Client.SendAsync(requestMessage); + response.StatusCode.ShouldBe(expectedStatusCode); + return response; + } + } +} diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs index ecc52d1f26e..d6c7a3a0a69 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Volo.Abp; @@ -39,7 +40,7 @@ public override void ConfigureServices(ServiceConfigurationContext context) options.EtoMappings.Add(typeof(DocsDomainModule)); options.EtoMappings.Add(typeof(DocsDomainModule)); }); - + Configure(options => { options.FileSets @@ -65,6 +66,18 @@ public override void ConfigureServices(ServiceConfigurationContext context) }); } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + using (var scope = context.ServiceProvider.CreateScope()) + { + if (scope.ServiceProvider.GetRequiredService>().Value.Enable) + { + var documentFullSearch = scope.ServiceProvider.GetRequiredService(); + await documentFullSearch.CreateIndexIfNeededAsync(); + } + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { using (var scope = context.ServiceProvider.CreateScope()) diff --git a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpIdentityServerDomainModule.cs b/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpIdentityServerDomainModule.cs index d3663277cbd..1f8fb93e4bf 100644 --- a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpIdentityServerDomainModule.cs +++ b/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpIdentityServerDomainModule.cs @@ -1,4 +1,5 @@ -using IdentityServer4.Services; +using System.Threading.Tasks; +using IdentityServer4.Services; using IdentityServer4.Stores; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -133,17 +134,31 @@ public override void PostConfigureServices(ServiceConfigurationContext context) }); } - public override void OnApplicationInitialization(ApplicationInitializationContext context) + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { var options = context.ServiceProvider.GetRequiredService>().Value; if (options.IsCleanupEnabled) { - context.ServiceProvider + await context.ServiceProvider .GetRequiredService() - .Add( + .AddAsync( context.ServiceProvider .GetRequiredService() ); } } + + public override void OnApplicationInitialization(ApplicationInitializationContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + if (options.IsCleanupEnabled) + { + AsyncHelper.RunSync(() => context.ServiceProvider + .GetRequiredService() + .AddAsync( + context.ServiceProvider + .GetRequiredService() + )); + } + } } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs index a64b17a3f9f..838c64e004a 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -9,7 +10,7 @@ namespace MyCompanyName.MyProjectName.Blazor.Server.Tiered; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -33,13 +34,13 @@ public static int Main(string[] args) builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); - builder.Services.AddApplication(options => + await builder.Services.AddApplicationAsync(options => { options.Services.ReplaceConfiguration(builder.Configuration); }); var app = builder.Build(); - app.InitializeApplication(); - app.Run(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs index ef9b6dcf353..b9aad1a4cd7 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -9,7 +10,7 @@ namespace MyCompanyName.MyProjectName.Blazor.Server; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -33,13 +34,13 @@ public static int Main(string[] args) builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); - builder.Services.AddApplication(options => + await builder.Services.AddApplicationAsync(options => { options.Services.ReplaceConfiguration(builder.Configuration); }); var app = builder.Build(); - app.InitializeApplication(); - app.Run(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs index 1ded7538360..12c8d2df84f 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs @@ -5,7 +5,7 @@ namespace MyCompanyName.MyProjectName.Blazor; public class Program { - public static async Task Main(string[] args) + public async static Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs index e6f48c54c2c..59b85f1a900 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -9,7 +10,7 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -33,13 +34,13 @@ public static int Main(string[] args) builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); - builder.Services.AddApplication(options => + await builder.Services.AddApplicationAsync(options => { options.Services.ReplaceConfiguration(builder.Configuration); }); var app = builder.Build(); - app.InitializeApplication(); - app.Run(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs index e6f48c54c2c..59b85f1a900 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -9,7 +10,7 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -33,13 +34,13 @@ public static int Main(string[] args) builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); - builder.Services.AddApplication(options => + await builder.Services.AddApplicationAsync(options => { options.Services.ReplaceConfiguration(builder.Configuration); }); var app = builder.Build(); - app.InitializeApplication(); - app.Run(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs index 499c2e2b41a..aca07693307 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -9,7 +10,7 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -33,13 +34,13 @@ public static int Main(string[] args) builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); - builder.Services.AddApplication(options => + await builder.Services.AddApplicationAsync(options => { options.Services.ReplaceConfiguration(builder.Configuration); }); var app = builder.Build(); - app.InitializeApplication(); - app.Run(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs index cdb4a395cc3..3cd8f691dcb 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -9,7 +10,7 @@ namespace MyCompanyName.MyProjectName.Web; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -33,13 +34,13 @@ public static int Main(string[] args) builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); - builder.Services.AddApplication(options => + await builder.Services.AddApplicationAsync(options => { options.Services.ReplaceConfiguration(builder.Configuration); }); var app = builder.Build(); - app.InitializeApplication(); - app.Run(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs index cdb4a395cc3..3cd8f691dcb 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -9,7 +10,7 @@ namespace MyCompanyName.MyProjectName.Web; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -33,13 +34,13 @@ public static int Main(string[] args) builder.Host.AddAppSettingsSecretsJson() .UseAutofac() .UseSerilog(); - builder.Services.AddApplication(options => + await builder.Services.AddApplicationAsync(options => { options.Services.ReplaceConfiguration(builder.Configuration); }); var app = builder.Build(); - app.InitializeApplication(); - app.Run(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs index d5b3c36ff54..39e7bdb524e 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs @@ -5,7 +5,7 @@ namespace MyCompanyName.MyProjectName.Blazor.Host; public class Program { - public static async Task Main(string[] args) + public async static Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/MyProjectNameBlazorHostModule.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/MyProjectNameBlazorHostModule.cs index 951a9e69bcc..fdb57b34359 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/MyProjectNameBlazorHostModule.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/MyProjectNameBlazorHostModule.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Net.Http; +using System.Threading.Tasks; using Blazorise.Bootstrap5; using Blazorise.Icons.FontAwesome; using Microsoft.AspNetCore.Builder; @@ -211,7 +212,7 @@ public override void ConfigureServices(ServiceConfigurationContext context) #endif } - public override void OnApplicationInitialization(ApplicationInitializationContext context) + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { var env = context.GetEnvironment(); var app = context.GetApplicationBuilder(); @@ -252,12 +253,9 @@ public override void OnApplicationInitialization(ApplicationInitializationContex using (var scope = context.ServiceProvider.CreateScope()) { - AsyncHelper.RunSync(async () => - { - await scope.ServiceProvider - .GetRequiredService() - .SeedAsync(); - }); + await scope.ServiceProvider + .GetRequiredService() + .SeedAsync(); } } } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Program.cs index 1301cbfb3e4..c1b5c178d55 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Program.cs @@ -1,6 +1,7 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -9,27 +10,37 @@ namespace MyCompanyName.MyProjectName.Blazor.Server.Host; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.Services.AddApplicationAsync(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,15 +53,4 @@ public static int Main(string[] args) Log.CloseAndFlush(); } } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Startup.cs deleted file mode 100644 index d356f6bede3..00000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Startup.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName.Blazor.Server.Host; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.InitializeApplication(); - } -} diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs index 500a2cfc000..328016c3b09 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs @@ -1,7 +1,7 @@ using System; -using System.IO; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -10,26 +10,37 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.Services.AddApplicationAsync(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +53,4 @@ public static int Main(string[] args) Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs deleted file mode 100644 index 200da6e5422..00000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/MyProjectNameIdentityServerModule.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/MyProjectNameIdentityServerModule.cs index b6fc071e142..eb854d3bc1b 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/MyProjectNameIdentityServerModule.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/MyProjectNameIdentityServerModule.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.DataProtection; @@ -187,7 +188,7 @@ public override void ConfigureServices(ServiceConfigurationContext context) #endif } - public override void OnApplicationInitialization(ApplicationInitializationContext context) + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = context.GetEnvironment(); @@ -227,19 +228,16 @@ public override void OnApplicationInitialization(ApplicationInitializationContex app.UseAbpSerilogEnrichers(); app.UseConfiguredEndpoints(); - SeedData(context); + await SeedData(context); } - private void SeedData(ApplicationInitializationContext context) + private async Task SeedData(ApplicationInitializationContext context) { - AsyncHelper.RunSync(async () => + using (var scope = context.ServiceProvider.CreateScope()) { - using (var scope = context.ServiceProvider.CreateScope()) - { - await scope.ServiceProvider - .GetRequiredService() - .SeedAsync(); - } - }); + await scope.ServiceProvider + .GetRequiredService() + .SeedAsync(); + } } } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Program.cs index 500a2cfc000..5f5b29332b9 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Program.cs @@ -1,7 +1,7 @@ using System; -using System.IO; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -10,26 +10,37 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.Services.AddApplicationAsync(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +53,4 @@ public static int Main(string[] args) Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Startup.cs deleted file mode 100644 index 70990fa4dac..00000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Startup.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Program.cs index 500a2cfc000..cdeeed1546d 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Program.cs @@ -1,7 +1,10 @@ using System; using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -10,26 +13,37 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.Services.AddApplicationAsync(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +56,4 @@ public static int Main(string[] args) Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Startup.cs deleted file mode 100644 index 265fb2e7d7d..00000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Startup.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/MyProjectNameWebUnifiedModule.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/MyProjectNameWebUnifiedModule.cs index ed4f5d13e91..49b63a407d7 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/MyProjectNameWebUnifiedModule.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/MyProjectNameWebUnifiedModule.cs @@ -1,5 +1,6 @@ using System.IO; using System.Reflection; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -140,7 +141,7 @@ public override void ConfigureServices(ServiceConfigurationContext context) #endif } - public override void OnApplicationInitialization(ApplicationInitializationContext context) + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = context.GetEnvironment(); @@ -180,12 +181,9 @@ public override void OnApplicationInitialization(ApplicationInitializationContex using (var scope = context.ServiceProvider.CreateScope()) { - AsyncHelper.RunSync(async () => - { - await scope.ServiceProvider - .GetRequiredService() - .SeedAsync(); - }); + await scope.ServiceProvider + .GetRequiredService() + .SeedAsync(); } } } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Program.cs index 6b523328cc3..a8443ddaca9 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Program.cs @@ -1,7 +1,10 @@ using System; using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -10,22 +13,37 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() +#if DEBUG .MinimumLevel.Debug() +#else + .MinimumLevel.Information() +#endif .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.Services.AddApplicationAsync(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -38,14 +56,4 @@ public static int Main(string[] args) Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Startup.cs deleted file mode 100644 index 2be66923ce6..00000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Startup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} From 9ee07d7019f216e5e8eddf3a9a678897a0c3572d Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 20 Dec 2021 20:18:46 +0800 Subject: [PATCH 06/13] Update AbpWebAssemblyHostBuilderExtensions.cs --- .../AbpWebAssemblyHostBuilderExtensions.cs | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Microsoft/AspNetCore/Components/WebAssembly/Hosting/AbpWebAssemblyHostBuilderExtensions.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Microsoft/AspNetCore/Components/WebAssembly/Hosting/AbpWebAssemblyHostBuilderExtensions.cs index cb104533cbe..7c4ff4a868e 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Microsoft/AspNetCore/Components/WebAssembly/Hosting/AbpWebAssemblyHostBuilderExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Microsoft/AspNetCore/Components/WebAssembly/Hosting/AbpWebAssemblyHostBuilderExtensions.cs @@ -17,6 +17,30 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting; public static class AbpWebAssemblyHostBuilderExtensions { + public static async Task AddApplicationAsync( + [NotNull] this WebAssemblyHostBuilder builder, + Action options) + where TStartupModule : IAbpModule + { + Check.NotNull(builder, nameof(builder)); + + // Related this commit(https://github.com/dotnet/aspnetcore/commit/b99d805bc037fcac56afb79abeb7d5a43141c85e) + // Microsoft.AspNetCore.Blazor.BuildTools has been removed in net 5.0. + // This call may be removed when we find a suitable solution. + // System.Runtime.CompilerServices.AsyncStateMachineAttribute + Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(); + + builder.Services.AddSingleton(builder.Configuration); + builder.Services.AddSingleton(builder); + + var application = await builder.Services.AddApplicationAsync(opts => + { + options?.Invoke(new AbpWebAssemblyApplicationCreationOptions(builder, opts)); + }); + + return application; + } + public static IAbpApplicationWithExternalServiceProvider AddApplication( [NotNull] this WebAssemblyHostBuilder builder, Action options) @@ -51,7 +75,7 @@ public static async Task InitializeAsync( ((ComponentsClientScopeServiceProviderAccessor)serviceProvider .GetRequiredService()).ServiceProvider = serviceProvider; - application.Initialize(serviceProvider); + await application.InitializeAsync(serviceProvider); await InitializeModulesAsync(serviceProvider); await SetCurrentLanguageAsync(serviceProvider); } From 003edef89720db85fd5c5b66cc298d7792fdff58 Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 20 Dec 2021 20:21:34 +0800 Subject: [PATCH 07/13] Use `AddApplicationAsync` in Blazor WASM. --- .../src/MyCompanyName.MyProjectName.Blazor/Program.cs | 2 +- .../host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs index 12c8d2df84f..027cac3dcf0 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs @@ -9,7 +9,7 @@ public async static Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); - var application = builder.AddApplication(options => + var application = await builder.AddApplicationAsync(options => { options.UseAutofac(); }); diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs index 39e7bdb524e..d0e58677bd0 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs @@ -9,7 +9,7 @@ public async static Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); - var application = builder.AddApplication(options => + var application = await builder.AddApplicationAsync(options => { options.UseAutofac(); }); From 7481d363b08be045a8b48455c08c68156529fa65 Mon Sep 17 00:00:00 2001 From: maliming Date: Tue, 21 Dec 2021 10:20:50 +0800 Subject: [PATCH 08/13] Add `AbpAsyncIntegratedTest`. --- .../AbpAspNetCoreAsyncIntegratedTestBase.cs | 24 +++---- .../AbpAspNetCoreIntegratedTestBase.cs | 2 - .../Abp/AbpTestBaseWithServiceProvider.cs | 2 +- .../Abp/Testing/AbpAsyncIntegratedTest.cs | 70 +++++++++++++++++++ .../Volo/Abp/Testing/AbpIntegratedTest.cs | 3 +- .../Interception/Autofac_Interception_Test.cs | 8 ++- .../DynamicProxy/AbpInterceptionTestBase.cs | 6 +- 7 files changed, 90 insertions(+), 25 deletions(-) create mode 100644 framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpAsyncIntegratedTest.cs diff --git a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs index 06a46897fac..3f5e9ad4b84 100644 --- a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs +++ b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs @@ -14,9 +14,9 @@ namespace Volo.Abp.AspNetCore.TestBase; public class AbpAspNetCoreAsyncIntegratedTestBase - where TModule : AbpModule + where TModule : IAbpModule { - protected IHost Host { get; set; } + protected WebApplication WebApplication { get; set; } protected TestServer Server { get; set; } @@ -50,26 +50,20 @@ await builder.Services.AddApplicationAsync(options => }); await ConfigureServicesAsync(builder.Services); + WebApplication = builder.Build(); + await WebApplication.InitializeApplicationAsync(); + await WebApplication.StartAsync(); - var app = builder.Build(); - - await app.InitializeApplicationAsync(); - - await app.StartAsync(); - - Host = app.Services.GetRequiredService(); - - Server = Host.GetTestServer(); - Client = Host.GetTestClient(); + Server = WebApplication.Services.GetRequiredService().GetTestServer(); + Client = Server.CreateClient(); ServiceProvider = Server.Services; - ServiceProvider.GetRequiredService().Server = Server; } - public virtual Task DisposeAsync() + public virtual async Task DisposeAsync() { - return Task.CompletedTask; + await WebApplication.DisposeAsync(); } protected virtual Task ConfigureServicesAsync(IServiceCollection services) diff --git a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreIntegratedTestBase.cs b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreIntegratedTestBase.cs index 1fa62b24170..f3e60979bbc 100644 --- a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreIntegratedTestBase.cs +++ b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreIntegratedTestBase.cs @@ -17,8 +17,6 @@ public abstract class AbpAspNetCoreIntegratedTestBase : AbpTestBaseWit protected HttpClient Client { get; } - protected override IServiceProvider ServiceProvider { get; } - private readonly IHost _host; protected AbpAspNetCoreIntegratedTestBase() diff --git a/framework/src/Volo.Abp.TestBase/Volo/Abp/AbpTestBaseWithServiceProvider.cs b/framework/src/Volo.Abp.TestBase/Volo/Abp/AbpTestBaseWithServiceProvider.cs index 6167d823cb3..407660e8545 100644 --- a/framework/src/Volo.Abp.TestBase/Volo/Abp/AbpTestBaseWithServiceProvider.cs +++ b/framework/src/Volo.Abp.TestBase/Volo/Abp/AbpTestBaseWithServiceProvider.cs @@ -5,7 +5,7 @@ namespace Volo.Abp; public abstract class AbpTestBaseWithServiceProvider { - protected abstract IServiceProvider ServiceProvider { get; } + protected IServiceProvider ServiceProvider { get; set; } protected virtual T GetService() { diff --git a/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpAsyncIntegratedTest.cs b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpAsyncIntegratedTest.cs new file mode 100644 index 00000000000..4238a8712b5 --- /dev/null +++ b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpAsyncIntegratedTest.cs @@ -0,0 +1,70 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.Modularity; + +namespace Volo.Abp.Testing; + +public class AbpAsyncIntegratedTest : AbpTestBaseWithServiceProvider + where TStartupModule : IAbpModule +{ + protected IAbpApplication Application { get; set; } + + protected IServiceProvider RootServiceProvider { get; set; } + + protected IServiceScope TestServiceScope { get; set; } + + public virtual async Task InitializeAsync() + { + var services = await CreateServiceCollectionAsync(); + + await BeforeAddApplicationAsync(services); + var application = await services.AddApplicationAsync(await SetAbpApplicationCreationOptionsAsync()); + await AfterAddApplicationAsync(services); + + RootServiceProvider = await CreateServiceProviderAsync(services); + TestServiceScope = RootServiceProvider.CreateScope(); + await application.InitializeAsync(TestServiceScope.ServiceProvider); + ServiceProvider = application.ServiceProvider; + Application = application; + + await InitializeServicesAsync(); + } + + public virtual async Task DisposeAsync() + { + await Application.ShutdownAsync(); + TestServiceScope.Dispose(); + Application.Dispose(); + } + + protected virtual Task CreateServiceCollectionAsync() + { + return Task.FromResult(new ServiceCollection()); + } + + protected virtual Task BeforeAddApplicationAsync(IServiceCollection services) + { + return Task.CompletedTask; + } + + protected virtual Task> SetAbpApplicationCreationOptionsAsync() + { + return Task.FromResult>(_ => { }); + } + + protected virtual Task AfterAddApplicationAsync(IServiceCollection services) + { + return Task.CompletedTask; + } + + protected virtual Task CreateServiceProviderAsync(IServiceCollection services) + { + return Task.FromResult(services.BuildServiceProviderFromFactory()); + } + + protected virtual Task InitializeServicesAsync() + { + return Task.CompletedTask; + } +} diff --git a/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs index bb085f6f741..b6ff2b8dbef 100644 --- a/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs +++ b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs @@ -9,8 +9,6 @@ public abstract class AbpIntegratedTest : AbpTestBaseWithService { protected IAbpApplication Application { get; } - protected override IServiceProvider ServiceProvider => Application.ServiceProvider; - protected IServiceProvider RootServiceProvider { get; } protected IServiceScope TestServiceScope { get; } @@ -29,6 +27,7 @@ protected AbpIntegratedTest() RootServiceProvider = CreateServiceProvider(services); TestServiceScope = RootServiceProvider.CreateScope(); + ServiceProvider = Application.ServiceProvider; application.Initialize(TestServiceScope.ServiceProvider); } diff --git a/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interception_Test.cs b/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interception_Test.cs index a7a2dfafbcb..290abda61bd 100644 --- a/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interception_Test.cs +++ b/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interception_Test.cs @@ -1,11 +1,13 @@ -using Volo.Abp.DynamicProxy; +using System; +using System.Threading.Tasks; +using Volo.Abp.DynamicProxy; namespace Volo.Abp.Autofac.Interception; public class Autofac_Interception_Test : AbpInterceptionTestBase { - protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) + protected override Task> SetAbpApplicationCreationOptionsAsync() { - options.UseAutofac(); + return Task.FromResult>(options => options.UseAutofac()); } } diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionTestBase.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionTestBase.cs index befc9af679f..f4b584701f2 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionTestBase.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionTestBase.cs @@ -7,10 +7,10 @@ namespace Volo.Abp.DynamicProxy; -public abstract class AbpInterceptionTestBase : AbpIntegratedTest +public abstract class AbpInterceptionTestBase : AbpAsyncIntegratedTest, IAsyncLifetime where TStartupModule : IAbpModule { - protected override void BeforeAddApplication(IServiceCollection services) + protected override Task BeforeAddApplicationAsync(IServiceCollection services) { services.AddTransient(); services.AddTransient(); @@ -32,6 +32,8 @@ protected override void BeforeAddApplication(IServiceCollection services) registration.Interceptors.Add(); } }); + + return Task.CompletedTask; } [Fact] From fa9e32db8ec502d52abc1ef05711131cade435a8 Mon Sep 17 00:00:00 2001 From: maliming Date: Tue, 21 Dec 2021 10:42:58 +0800 Subject: [PATCH 09/13] Update AbpIntegratedTest.cs --- .../src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs index b6ff2b8dbef..8d8612c5b96 100644 --- a/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs +++ b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs @@ -27,8 +27,8 @@ protected AbpIntegratedTest() RootServiceProvider = CreateServiceProvider(services); TestServiceScope = RootServiceProvider.CreateScope(); - ServiceProvider = Application.ServiceProvider; application.Initialize(TestServiceScope.ServiceProvider); + ServiceProvider = Application.ServiceProvider; } protected virtual IServiceCollection CreateServiceCollection() From dbb02fa744d214854305d958e13823ea618f40bf Mon Sep 17 00:00:00 2001 From: maliming Date: Fri, 24 Dec 2021 11:29:33 +0800 Subject: [PATCH 10/13] Update the Console and WPF template. --- .../HelloWorldService.cs | 16 ++++- .../MyProjectNameHostedService.cs | 58 ++++++++++------- .../MyProjectNameModule.cs | 18 ++++-- .../MyCompanyName.MyProjectName/Program.cs | 26 +++----- .../appsettings.json | 2 +- .../MyCompanyName.MyProjectName/App.xaml.cs | 63 ++++++++----------- .../HelloWorldService.cs | 13 +++- 7 files changed, 110 insertions(+), 86 deletions(-) diff --git a/templates/console/src/MyCompanyName.MyProjectName/HelloWorldService.cs b/templates/console/src/MyCompanyName.MyProjectName/HelloWorldService.cs index 7ddd618c3e3..7c095b85ed4 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/HelloWorldService.cs +++ b/templates/console/src/MyCompanyName.MyProjectName/HelloWorldService.cs @@ -1,12 +1,22 @@ -using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Volo.Abp.DependencyInjection; namespace MyCompanyName.MyProjectName; public class HelloWorldService : ITransientDependency { - public void SayHello() + public ILogger Logger { get; set; } + + public HelloWorldService() + { + Logger = NullLogger.Instance; + } + + public Task SayHelloAsync() { - Console.WriteLine("\tHello World!"); + Logger.LogInformation("Hello World!"); + return Task.CompletedTask; } } diff --git a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs index 822844e10e4..318e5a5508f 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs +++ b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs @@ -1,40 +1,56 @@ -using System; -using System.Threading; +using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Extensions.Hosting; +using Serilog.Extensions.Logging; using Volo.Abp; namespace MyCompanyName.MyProjectName; public class MyProjectNameHostedService : IHostedService { - private readonly IAbpApplicationWithExternalServiceProvider _application; - private readonly IServiceProvider _serviceProvider; - private readonly HelloWorldService _helloWorldService; - - public MyProjectNameHostedService( - IAbpApplicationWithExternalServiceProvider application, - IServiceProvider serviceProvider, - HelloWorldService helloWorldService) + private IAbpApplicationWithInternalServiceProvider _abpApplication; + + private readonly IConfiguration _configuration; + private readonly IHostEnvironment _hostEnvironment; + + public MyProjectNameHostedService(IConfiguration configuration, IHostEnvironment hostEnvironment) { - _application = application; - _serviceProvider = serviceProvider; - _helloWorldService = helloWorldService; + _configuration = configuration; + _hostEnvironment = hostEnvironment; } - public Task StartAsync(CancellationToken cancellationToken) + public async Task StartAsync(CancellationToken cancellationToken) { - _application.Initialize(_serviceProvider); + _abpApplication = await AbpApplicationFactory.CreateAsync(options => + { + options.Services.ReplaceConfiguration(_configuration); + options.Services.AddSingleton(_hostEnvironment); + + options.UseAutofac(); - _helloWorldService.SayHello(); + // UseSerilog() + options.Services.AddLogging(); + options.Services.Replace(ServiceDescriptor.Singleton()); + var implementationInstance = new DiagnosticContext(null); + options.Services.AddSingleton(implementationInstance); + options.Services.AddSingleton((IDiagnosticContext) implementationInstance); + }); - return Task.CompletedTask; + await _abpApplication.InitializeAsync(); + + var helloWorldService = _abpApplication.ServiceProvider.GetRequiredService(); + + await helloWorldService.SayHelloAsync(); } - public Task StopAsync(CancellationToken cancellationToken) + public async Task StopAsync(CancellationToken cancellationToken) { - _application.Shutdown(); - - return Task.CompletedTask; + await _abpApplication.ShutdownAsync(); } } diff --git a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameModule.cs b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameModule.cs index 15ff448d74d..c7045a62eaa 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameModule.cs +++ b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameModule.cs @@ -1,5 +1,9 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Volo.Abp; using Volo.Abp.Autofac; using Volo.Abp.Modularity; @@ -10,11 +14,15 @@ namespace MyCompanyName.MyProjectName; )] public class MyProjectNameModule : AbpModule { - public override void ConfigureServices(ServiceConfigurationContext context) + public override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { - var configuration = context.Services.GetConfiguration(); - var hostEnvironment = context.Services.GetSingletonInstance(); + var logger = context.ServiceProvider.GetRequiredService>(); + var configuration = context.ServiceProvider.GetRequiredService(); + logger.LogInformation($"MySettingName => {configuration["MySettingName"]}"); - context.Services.AddHostedService(); + var hostEnvironment = context.ServiceProvider.GetRequiredService(); + logger.LogInformation($"EnvironmentName => {hostEnvironment.EnvironmentName}"); + + return Task.CompletedTask; } } diff --git a/templates/console/src/MyCompanyName.MyProjectName/Program.cs b/templates/console/src/MyCompanyName.MyProjectName/Program.cs index 1ec4de497cb..c6317e635d6 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/Program.cs +++ b/templates/console/src/MyCompanyName.MyProjectName/Program.cs @@ -1,6 +1,5 @@ using System; using System.Threading.Tasks; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; @@ -10,7 +9,7 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static async Task Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -27,7 +26,14 @@ public static async Task Main(string[] args) try { Log.Information("Starting console host."); - await CreateHostBuilder(args).RunConsoleAsync(); + + await Host.CreateDefaultBuilder(args) + .ConfigureServices(services => + { + services.AddHostedService(); + }) + .RunConsoleAsync(); + return 0; } catch (Exception ex) @@ -39,19 +45,5 @@ public static async Task Main(string[] args) { Log.CloseAndFlush(); } - } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .UseAutofac() - .UseSerilog() - .ConfigureAppConfiguration((context, config) => - { - //setup your additional configuration sources - }) - .ConfigureServices((hostContext, services) => - { - services.AddApplication(); - }); } diff --git a/templates/console/src/MyCompanyName.MyProjectName/appsettings.json b/templates/console/src/MyCompanyName.MyProjectName/appsettings.json index 0db3279e44b..1bc4c59014e 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/appsettings.json +++ b/templates/console/src/MyCompanyName.MyProjectName/appsettings.json @@ -1,3 +1,3 @@ { - + "MySettingName": "MySettingValue" } diff --git a/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs b/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs index ab80f115c1b..46ddd64910a 100644 --- a/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs +++ b/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs @@ -1,9 +1,12 @@ using System; using System.Windows; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Serilog; using Serilog.Events; +using Serilog.Extensions.Hosting; +using Serilog.Extensions.Logging; using Volo.Abp; namespace MyCompanyName.MyProjectName; @@ -13,35 +16,40 @@ namespace MyCompanyName.MyProjectName; /// public partial class App : Application { - private readonly IHost _host; - private readonly IAbpApplicationWithExternalServiceProvider _application; + private IAbpApplicationWithInternalServiceProvider _abpApplication; - public App() + protected async override void OnStartup(StartupEventArgs e) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) .CreateLogger(); - _host = CreateHostBuilder(); - _application = _host.Services.GetService(); - } - - protected override async void OnStartup(StartupEventArgs e) - { try { Log.Information("Starting WPF host."); - await _host.StartAsync(); - Initialize(_host.Services); - _host.Services.GetService()?.Show(); + _abpApplication = await AbpApplicationFactory.CreateAsync(options => + { + options.UseAutofac(); + + // UseSerilog() + options.Services.AddLogging(); + options.Services.Replace(ServiceDescriptor.Singleton()); + var implementationInstance = new DiagnosticContext(null); + options.Services.AddSingleton(implementationInstance); + options.Services.AddSingleton((IDiagnosticContext) implementationInstance); + }); + + await _abpApplication.InitializeAsync(); + + _abpApplication.Services.GetRequiredService()?.Show(); } catch (Exception ex) @@ -50,28 +58,9 @@ protected override async void OnStartup(StartupEventArgs e) } } - protected override async void OnExit(ExitEventArgs e) + protected async override void OnExit(ExitEventArgs e) { - _application.Shutdown(); - await _host.StopAsync(); - _host.Dispose(); + await _abpApplication.ShutdownAsync(); Log.CloseAndFlush(); } - - private void Initialize(IServiceProvider serviceProvider) - { - _application.Initialize(serviceProvider); - } - - private IHost CreateHostBuilder() - { - return Host - .CreateDefaultBuilder(null) - .UseAutofac() - .UseSerilog() - .ConfigureServices((hostContext, services) => - { - services.AddApplication(); - }).Build(); - } } diff --git a/templates/wpf/src/MyCompanyName.MyProjectName/HelloWorldService.cs b/templates/wpf/src/MyCompanyName.MyProjectName/HelloWorldService.cs index 35127360b8d..2c88a265e0e 100644 --- a/templates/wpf/src/MyCompanyName.MyProjectName/HelloWorldService.cs +++ b/templates/wpf/src/MyCompanyName.MyProjectName/HelloWorldService.cs @@ -1,11 +1,20 @@ -using Volo.Abp.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Volo.Abp.DependencyInjection; namespace MyCompanyName.MyProjectName; public class HelloWorldService : ITransientDependency { + public ILogger Logger { get; set; } + + public HelloWorldService() + { + Logger = NullLogger.Instance; + } public string SayHello() { - return "\tHello world!"; + Logger.LogInformation("Call SayHello"); + return "Hello world!"; } } From 0c5482c23fe63f6614a82c3a20aacf8be2127651 Mon Sep 17 00:00:00 2001 From: maliming Date: Fri, 24 Dec 2021 13:06:17 +0800 Subject: [PATCH 11/13] Use `AddSerilog`. --- .../MyCompanyName.MyProjectName.csproj | 1 + .../MyProjectNameHostedService.cs | 12 +----------- .../wpf/src/MyCompanyName.MyProjectName/App.xaml.cs | 12 +----------- .../MyCompanyName.MyProjectName.csproj | 1 + 4 files changed, 4 insertions(+), 22 deletions(-) diff --git a/templates/console/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj b/templates/console/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj index 2ea0513d714..a2041bf9708 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj +++ b/templates/console/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj @@ -14,6 +14,7 @@ + diff --git a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs index 318e5a5508f..756d56571e8 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs +++ b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs @@ -2,12 +2,8 @@ using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; using Serilog; -using Serilog.Extensions.Hosting; -using Serilog.Extensions.Logging; using Volo.Abp; namespace MyCompanyName.MyProjectName; @@ -33,13 +29,7 @@ public async Task StartAsync(CancellationToken cancellationToken) options.Services.AddSingleton(_hostEnvironment); options.UseAutofac(); - - // UseSerilog() - options.Services.AddLogging(); - options.Services.Replace(ServiceDescriptor.Singleton()); - var implementationInstance = new DiagnosticContext(null); - options.Services.AddSingleton(implementationInstance); - options.Services.AddSingleton((IDiagnosticContext) implementationInstance); + options.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true)); }); await _abpApplication.InitializeAsync(); diff --git a/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs b/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs index 46ddd64910a..21124d6400a 100644 --- a/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs +++ b/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs @@ -1,12 +1,8 @@ using System; using System.Windows; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Logging; using Serilog; using Serilog.Events; -using Serilog.Extensions.Hosting; -using Serilog.Extensions.Logging; using Volo.Abp; namespace MyCompanyName.MyProjectName; @@ -38,13 +34,7 @@ protected async override void OnStartup(StartupEventArgs e) _abpApplication = await AbpApplicationFactory.CreateAsync(options => { options.UseAutofac(); - - // UseSerilog() - options.Services.AddLogging(); - options.Services.Replace(ServiceDescriptor.Singleton()); - var implementationInstance = new DiagnosticContext(null); - options.Services.AddSingleton(implementationInstance); - options.Services.AddSingleton((IDiagnosticContext) implementationInstance); + options.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true)); }); await _abpApplication.InitializeAsync(); diff --git a/templates/wpf/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj b/templates/wpf/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj index afb8fcfb4cf..6b5352c3e7d 100644 --- a/templates/wpf/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj +++ b/templates/wpf/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj @@ -15,6 +15,7 @@ + From 59284b463ad9483e606618bd53acfaafc7829bc0 Mon Sep 17 00:00:00 2001 From: maliming Date: Fri, 24 Dec 2021 15:04:26 +0800 Subject: [PATCH 12/13] Use `AsyncHelper` for `ShutdownAsync`. --- .../AspNetCore/Builder/AbpApplicationBuilderExtensions.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs index b15167fa1df..8ef3ec8d990 100644 --- a/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs @@ -12,6 +12,7 @@ using Volo.Abp.AspNetCore.Tracing; using Volo.Abp.AspNetCore.Uow; using Volo.Abp.DependencyInjection; +using Volo.Abp.Threading; namespace Microsoft.AspNetCore.Builder; @@ -29,7 +30,7 @@ public async static Task InitializeApplicationAsync([NotNull] this IApplicationB applicationLifetime.ApplicationStopping.Register(() => { - application.ShutdownAsync(); + AsyncHelper.RunSync(() => application.ShutdownAsync()); }); applicationLifetime.ApplicationStopped.Register(() => From d9a5b86505c194080331e74bdc34d392cfd5be93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Halil=20=C4=B0brahim=20Kalkan?= Date: Sat, 25 Dec 2021 12:30:09 +0300 Subject: [PATCH 13/13] Check multiple configure services calls and rename ManualConfigureServices to SkipConfigureServices. --- .../Volo/Abp/AbpApplicationBase.cs | 20 ++++++++++++++++++- .../Volo/Abp/AbpApplicationCreationOptions.cs | 3 +-- .../Volo/Abp/AbpApplicationFactory.cs | 8 ++++---- .../Volo.Abp.Core/Volo/Abp/IAbpApplication.cs | 7 +++++++ ...pApplicationWithExternalServiceProvider.cs | 7 +------ ...pApplicationWithInternalServiceProvider.cs | 5 ----- 6 files changed, 32 insertions(+), 18 deletions(-) diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs index c6e86b4af86..2a73b729323 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs @@ -24,6 +24,8 @@ public abstract class AbpApplicationBase : IAbpApplication public IReadOnlyList Modules { get; } + private bool _configuredServices; + internal AbpApplicationBase( [NotNull] Type startupModuleType, [NotNull] IServiceCollection services, @@ -48,7 +50,7 @@ internal AbpApplicationBase( Modules = LoadModules(services, options); - if (!options.ManualConfigureServices) + if (!options.SkipConfigureServices) { ConfigureServices(); } @@ -139,6 +141,8 @@ protected virtual IReadOnlyList LoadModules(IServiceCollec //TODO: We can extract a new class for this public virtual async Task ConfigureServicesAsync() { + CheckMultipleConfigureServices(); + var context = new ServiceConfigurationContext(Services); Services.AddSingleton(context); @@ -211,11 +215,23 @@ public virtual async Task ConfigureServicesAsync() abpModule.ServiceConfigurationContext = null; } } + + _configuredServices = true; + } + + private void CheckMultipleConfigureServices() + { + if (_configuredServices) + { + throw new AbpInitializationException("Services have already been configured! If you call ConfigureServicesAsync method, you must have set AbpApplicationCreationOptions.SkipConfigureServices tu true before."); + } } //TODO: We can extract a new class for this public virtual void ConfigureServices() { + CheckMultipleConfigureServices(); + var context = new ServiceConfigurationContext(Services); Services.AddSingleton(context); @@ -288,5 +304,7 @@ public virtual void ConfigureServices() abpModule.ServiceConfigurationContext = null; } } + + _configuredServices = true; } } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs index 8bf75798433..d18e43275b4 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs @@ -19,13 +19,12 @@ public class AbpApplicationCreationOptions [NotNull] public AbpConfigurationBuilderOptions Configuration { get; } - public bool ManualConfigureServices { get; set; } + public bool SkipConfigureServices { get; set; } public AbpApplicationCreationOptions([NotNull] IServiceCollection services) { Services = Check.NotNull(services, nameof(services)); PlugInSources = new PlugInSourceList(); Configuration = new AbpConfigurationBuilderOptions(); - ManualConfigureServices = false; } } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs index d904c24ca27..50e5e862cae 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs @@ -15,7 +15,7 @@ public async static Task CreateAsync var app = Create(typeof(TStartupModule), options => { optionsAction?.Invoke(options); - options.ManualConfigureServices = true; + options.SkipConfigureServices = true; }); await app.ConfigureServicesAsync(); return app; @@ -28,7 +28,7 @@ public async static Task CreateAsync var app = new AbpApplicationWithInternalServiceProvider(startupModuleType, options => { optionsAction?.Invoke(options); - options.ManualConfigureServices = true; + options.SkipConfigureServices = true; }); await app.ConfigureServicesAsync(); return app; @@ -42,7 +42,7 @@ public async static Task CreateAsync var app = Create(typeof(TStartupModule), services, options => { optionsAction?.Invoke(options); - options.ManualConfigureServices = true; + options.SkipConfigureServices = true; }); await app.ConfigureServicesAsync(); return app; @@ -56,7 +56,7 @@ public async static Task CreateAsync var app = new AbpApplicationWithExternalServiceProvider(startupModuleType, services, options => { optionsAction?.Invoke(options); - options.ManualConfigureServices = true; + options.SkipConfigureServices = true; }); await app.ConfigureServicesAsync(); return app; diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs index b51fd7ec37b..2fb66b735f9 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs @@ -23,6 +23,13 @@ public interface IAbpApplication : IModuleContainer, IDisposable /// This can not be used before initialize the application. /// IServiceProvider ServiceProvider { get; } + + /// + /// Calls the Pre/Post/ConfigureServicesAsync methods of the modules. + /// If you use this method, you must have set the + /// option to true before. + /// + Task ConfigureServicesAsync(); /// /// Used to gracefully shutdown the application and all modules. diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs index b4363e1161a..a17bb146e30 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs @@ -10,12 +10,7 @@ public interface IAbpApplicationWithExternalServiceProvider : IAbpApplication /// Sets the service provider, but not initializes the modules. /// void SetServiceProvider([NotNull] IServiceProvider serviceProvider); - - /// - /// Call the Pre/Post/ConfigureServicesAsync method of the modules. - /// - Task ConfigureServicesAsync(); - + /// /// Sets the service provider and initializes all the modules. /// If was called before, the same diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs index 8a3b4c7ca1d..0079608c2ea 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs @@ -11,11 +11,6 @@ public interface IAbpApplicationWithInternalServiceProvider : IAbpApplication /// IServiceProvider CreateServiceProvider(); - /// - /// Call the Pre/Post/ConfigureServicesAsync method of the modules. - /// - Task ConfigureServicesAsync(); - /// /// Creates the service provider and initializes all the modules. /// If method was called before,