├── .github └── workflows │ ├── build.yml │ └── release.yml ├── .gitignore ├── Extensions.Hosting.AsyncInitialization.sln ├── LICENSE.txt ├── README.md ├── build.cmd ├── build.ps1 ├── src └── Extensions.Hosting.AsyncInitialization │ ├── DependencyInjection │ └── AsyncInitializationServiceCollectionExtensions.cs │ ├── Extensions.Hosting.AsyncInitialization.csproj │ ├── Hosting │ └── AsyncInitializationHostExtensions.cs │ ├── IAsyncInitializer.cs │ ├── IAsyncTeardown.cs │ └── RootInitializer.cs ├── tests └── Extensions.Hosting.AsyncInitialization.Tests │ ├── AsyncInitializationAndRunTests.cs │ ├── AsyncInitializationTests.cs │ ├── AsyncTeardownTests.cs │ ├── CommonTestTypes.cs │ └── Extensions.Hosting.AsyncInitialization.Tests.csproj └── tools └── build ├── Build.cs ├── Program.cs └── build.csproj /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: 3 | pull_request: 4 | push: 5 | branches: [master] 6 | workflow_call: 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v4 13 | - name: Run build script 14 | shell: pwsh 15 | run: ./build.ps1 16 | - name: Upload packages 17 | uses: actions/upload-artifact@v4 18 | with: 19 | name: packages 20 | path: artifacts/packages/*.nupkg 21 | - name: Upload build logs 22 | if: always() 23 | uses: actions/upload-artifact@v4 24 | with: 25 | name: build-logs 26 | path: artifacts/logs/*.binlog 27 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | release: 4 | types: [published] 5 | jobs: 6 | build: 7 | uses: ./.github/workflows/build.yml 8 | release: 9 | needs: build 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Download artifact 13 | uses: actions/download-artifact@v4 14 | with: 15 | name: packages 16 | - name: Publish to NuGet 17 | run: dotnet nuget push *.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | obj/ 3 | .vs/ 4 | .vscode/ 5 | *.user 6 | 7 | artifacts/ 8 | 9 | _ReSharper.Caches/ 10 | -------------------------------------------------------------------------------- /Extensions.Hosting.AsyncInitialization.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.6.33815.320 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{F3949869-0B22-4F63-8B97-B3548E7ED0AC}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Extensions.Hosting.AsyncInitialization", "src\Extensions.Hosting.AsyncInitialization\Extensions.Hosting.AsyncInitialization.csproj", "{DEC4A732-9A80-4CC9-9775-D3A8CE65F633}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{81FBB26C-5751-4F6E-8B10-4BD7AC3888FC}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Extensions.Hosting.AsyncInitialization.Tests", "tests\Extensions.Hosting.AsyncInitialization.Tests\Extensions.Hosting.AsyncInitialization.Tests.csproj", "{8264807E-AEEC-4A9F-8023-7B30B01F3FD2}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{ACEAE2B6-8261-4C7F-968F-35D5221929D6}" 15 | ProjectSection(SolutionItems) = preProject 16 | .gitignore = .gitignore 17 | build.cmd = build.cmd 18 | LICENSE.txt = LICENSE.txt 19 | README.md = README.md 20 | build.ps1 = build.ps1 21 | EndProjectSection 22 | EndProject 23 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{C6A2E948-78A9-4E82-B112-A00F93A94496}" 24 | EndProject 25 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "build", "tools\build\build.csproj", "{191B7D1C-7505-404B-8805-DD8E3EB44785}" 26 | EndProject 27 | Global 28 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 29 | Debug|Any CPU = Debug|Any CPU 30 | Release|Any CPU = Release|Any CPU 31 | EndGlobalSection 32 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 33 | {DEC4A732-9A80-4CC9-9775-D3A8CE65F633}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {DEC4A732-9A80-4CC9-9775-D3A8CE65F633}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {DEC4A732-9A80-4CC9-9775-D3A8CE65F633}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {DEC4A732-9A80-4CC9-9775-D3A8CE65F633}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {8264807E-AEEC-4A9F-8023-7B30B01F3FD2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {8264807E-AEEC-4A9F-8023-7B30B01F3FD2}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {8264807E-AEEC-4A9F-8023-7B30B01F3FD2}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {8264807E-AEEC-4A9F-8023-7B30B01F3FD2}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {191B7D1C-7505-404B-8805-DD8E3EB44785}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {191B7D1C-7505-404B-8805-DD8E3EB44785}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | EndGlobalSection 44 | GlobalSection(SolutionProperties) = preSolution 45 | HideSolutionNode = FALSE 46 | EndGlobalSection 47 | GlobalSection(NestedProjects) = preSolution 48 | {DEC4A732-9A80-4CC9-9775-D3A8CE65F633} = {F3949869-0B22-4F63-8B97-B3548E7ED0AC} 49 | {8264807E-AEEC-4A9F-8023-7B30B01F3FD2} = {81FBB26C-5751-4F6E-8B10-4BD7AC3888FC} 50 | {191B7D1C-7505-404B-8805-DD8E3EB44785} = {C6A2E948-78A9-4E82-B112-A00F93A94496} 51 | EndGlobalSection 52 | GlobalSection(ExtensibilityGlobals) = postSolution 53 | SolutionGuid = {2CD1AD1C-0AF7-48E4-A9DE-4D22491B7292} 54 | EndGlobalSection 55 | EndGlobal 56 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Extensions.Hosting.AsyncInitialization 2 | 3 | [![NuGet version](https://img.shields.io/nuget/v/Extensions.Hosting.AsyncInitialization.svg?logo=nuget)](https://www.nuget.org/packages/Extensions.Hosting.AsyncInitialization) 4 | [![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/thomaslevesque/Extensions.Hosting.AsyncInitialization/build.yml?branch=master&logo=github)](https://github.com/thomaslevesque/Extensions.Hosting.AsyncInitialization/actions/workflows/build.yml) 5 | 6 | A simple helper to perform async application initialization and teardown for the generic host in .NET 6.0 or higher (e.g. in ASP.NET Core apps). 7 | 8 | ## Basic usage 9 | 10 | 1. Install the [Extensions.Hosting.AsyncInitialization](https://www.nuget.org/packages/Extensions.Hosting.AsyncInitialization/) NuGet package: 11 | 12 | Command line: 13 | 14 | ```PowerShell 15 | dotnet add package Extensions.Hosting.AsyncInitialization 16 | ``` 17 | 18 | Package manager console: 19 | ```PowerShell 20 | Install-Package Extensions.Hosting.AsyncInitialization 21 | ``` 22 | 23 | 24 | 2. Create a class (or several) that implements `IAsyncInitializer`. This class can depend on any registered service. 25 | 26 | ```csharp 27 | public class MyAppInitializer : IAsyncInitializer 28 | { 29 | public MyAppInitializer(IFoo foo, IBar bar) 30 | { 31 | ... 32 | } 33 | 34 | public async Task InitializeAsync(CancellationToken cancellationToken) 35 | { 36 | // Initialization code here 37 | } 38 | } 39 | ``` 40 | 41 | 3. Register your initializer(s) in the same place as other services: 42 | 43 | ```csharp 44 | services.AddAsyncInitializer(); 45 | ``` 46 | 47 | 4. In the `Program` class, replace the call to `host.RunAsync()` with `host.InitAndRunAsync()`: 48 | 49 | ```csharp 50 | public static async Task Main(string[] args) 51 | { 52 | var host = CreateHostBuilder(args).Build(); 53 | await host.InitAndRunAsync(); 54 | } 55 | ``` 56 | 57 | This will run each initializer, in the order in which they were registered. 58 | 59 | ## Teardown 60 | 61 | In addition to initialization, this library also supports performing cleanup tasks when the app terminates. To use this, make your initializer implement `IAsyncTeardown`, and implement the `TeardownAsync` method: 62 | 63 | 64 | ```csharp 65 | public class MyAppInitializer : IAsyncTeardown 66 | { 67 | public MyAppInitializer(IFoo foo, IBar bar) 68 | { 69 | ... 70 | } 71 | 72 | public async Task InitializeAsync(CancellationToken cancellationToken) 73 | { 74 | // Initialization code here 75 | } 76 | 77 | public async Task TeardownAsync(CancellationToken cancellationToken) 78 | { 79 | // Cleanup code here 80 | } 81 | } 82 | ``` 83 | 84 | When you run the application with `InitAndRunAsync`, each initializer that supports teardown will be invoked in reverse registration order, i.e.: 85 | 86 | - initializer 1 performs initialization 87 | - initializer 2 performs initialization 88 | - application runs 89 | - initializer 2 performs teardown 90 | - initializer 1 performs teardown 91 | 92 | ## Lifetime and state considerations 93 | 94 | When you create an initializer that also performs teardown, keep in mind that it will actually be resolved twice: 95 | - once for initialization 96 | - once for teardown 97 | 98 | Initialization and teardown each runs in its own service provider scope. This means that a different instance of your initializer will be used for initialization and teardown, so your initializer cannot keep state between initialization and teardown, unless it's registered as a singleton. 99 | 100 | If you do register your initializer as a singleton, keep in mind that it must not depend on any scoped service, otherwise the scoped service will live for the whole lifetime of the application; this is an anti-pattern known as [captive dependency](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#captive-dependency). 101 | 102 | ## Advanced usage 103 | 104 | If, for some reason, you need more control over the application execution process, you can manually call the `InitAsync` and `TeardownAsync` methods on the host. If you do that, keep in mind that `TeardownAsync` cannot be called after `host.RunAsync()` completes, because the host will already have been disposed: 105 | 106 | ```csharp 107 | // DO NOT DO THIS 108 | await host.InitAsync(); 109 | await host.RunAsync(); 110 | await host.TeardownAsync(); // Will fail because RunAsync disposed the host 111 | ``` 112 | 113 | So you will need to manually call `StartAsync` and `WaitForShutdownAsync`, and call `TeardownAsync` _before_ you dispose the host: 114 | 115 | ```csharp 116 | await using (var host = CreateHostBuilder(args).Build()) 117 | { 118 | await host.InitAsync(); 119 | await host.StartAsync(); 120 | await host.WaitForShutdownAsync(); 121 | await host.TeardownAsync(); 122 | } 123 | ``` 124 | 125 | ## Cancellation 126 | 127 | The `InitAndRunAsync`, `InitAsync` and `TeardownAsync` all support passing a cancellation token to abort execution if needed. Cancellation will be propagated to the initializers. 128 | 129 | In the following example, execution (including initialization, but not teardown) will be aborted when `Ctrl + C` keys are pressed : 130 | ```csharp 131 | public static async Task Main(string[] args) 132 | { 133 | using CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); 134 | 135 | // The following line will hook `Ctrl` + `C` to the cancellation token. 136 | Console.CancelKeyPress += (source, args) => cancellationTokenSource.Cancel(); 137 | 138 | var host = CreateHostBuilder(args).Build(); 139 | await host.InitAndRunAsync(cancellationTokenSource.Token); 140 | } 141 | ``` 142 | 143 | As mentioned above, when using `InitAndRunAsync`, the cancellation token will *not* be passed to the teardown. This is because when your application is stopped, you typically still want the teardown to occur. Instead, teardown will run with a default timeout of 10 seconds (you can also specify a timeout explicitly). 144 | 145 | If you don't want this behavior, you can manually call `InitAsync` and `TeardownAsync` as explained in the previous section. 146 | 147 | ### Migration from 2.x or earlier 148 | 149 | If you were already using this library prior to version 3.x, your code would typically look like this: 150 | 151 | ```csharp 152 | await host.InitAsync(); 153 | await host.RunAsync(); 154 | ``` 155 | 156 | This will still work without changes. Just keep in mind that, as explained in the Advanced Usage section, adding a call to `host.TeardownAsync()` after `host.RunAsync()` *will not work*. If you need teardown, the simplest way is to remove the explicit call to `InitAsync`, and call `InitAndRunAsync` instead of `RunAsync`. 157 | -------------------------------------------------------------------------------- /build.cmd: -------------------------------------------------------------------------------- 1 | @dotnet run --project "%~dp0\tools\build\build.csproj" -- %* 2 | -------------------------------------------------------------------------------- /build.ps1: -------------------------------------------------------------------------------- 1 | dotnet run --project "$PSScriptRoot/tools/build/build.csproj" -- @Args 2 | -------------------------------------------------------------------------------- /src/Extensions.Hosting.AsyncInitialization/DependencyInjection/AsyncInitializationServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.CodeAnalysis; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using Extensions.Hosting.AsyncInitialization; 6 | using Microsoft.Extensions.DependencyInjection.Extensions; 7 | 8 | // ReSharper disable once CheckNamespace 9 | namespace Microsoft.Extensions.DependencyInjection 10 | { 11 | /// 12 | /// Provides extension methods to register async initializers. 13 | /// 14 | public static class AsyncInitializationServiceCollectionExtensions 15 | { 16 | /// 17 | /// Registers necessary services for async initialization support. 18 | /// 19 | /// The to add the service to. 20 | /// A reference to this instance after the operation has completed. 21 | public static IServiceCollection AddAsyncInitialization(this IServiceCollection services) 22 | { 23 | if (services == null) 24 | throw new ArgumentNullException(nameof(services)); 25 | 26 | services.TryAddTransient(); 27 | return services; 28 | } 29 | 30 | /// 31 | /// Adds an async initializer of the specified type. 32 | /// 33 | /// The type of the async initializer to add. 34 | /// The to add the service to. 35 | /// The initializer's lifetime. Defaults to . 36 | /// A reference to this instance after the operation has completed. 37 | public static IServiceCollection AddAsyncInitializer<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]TInitializer>(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Transient) 38 | where TInitializer : class, IAsyncInitializer 39 | { 40 | return services 41 | .AddAsyncInitialization() 42 | .AddServiceDescriptor(ServiceDescriptor.Describe(typeof(IAsyncInitializer), typeof(TInitializer), lifetime)); 43 | } 44 | 45 | /// 46 | /// Adds the specified async initializer instance. 47 | /// 48 | /// The type of the async initializer to add. 49 | /// The to add the service to. 50 | /// The service initializer 51 | /// A reference to this instance after the operation has completed. 52 | public static IServiceCollection AddAsyncInitializer(this IServiceCollection services, TInitializer initializer) 53 | where TInitializer : class, IAsyncInitializer 54 | { 55 | if (initializer == null) 56 | throw new ArgumentNullException(nameof(initializer)); 57 | 58 | return services 59 | .AddAsyncInitialization() 60 | .AddSingleton(initializer); 61 | } 62 | 63 | /// 64 | /// Adds an async initializer with a factory specified in . 65 | /// 66 | /// The to add the service to. 67 | /// The factory that creates the async initializer. 68 | /// The initializer's lifetime. Defaults to . 69 | /// A reference to this instance after the operation has completed. 70 | public static IServiceCollection AddAsyncInitializer(this IServiceCollection services, Func implementationFactory, ServiceLifetime lifetime = ServiceLifetime.Transient) 71 | { 72 | if (implementationFactory == null) 73 | throw new ArgumentNullException(nameof(implementationFactory)); 74 | 75 | return services 76 | .AddAsyncInitialization() 77 | .AddServiceDescriptor(ServiceDescriptor.Describe(typeof(IAsyncInitializer), implementationFactory, lifetime)); 78 | } 79 | 80 | /// 81 | /// Adds an async initializer of the specified type 82 | /// 83 | /// The to add the service to. 84 | /// The type of the async initializer to add. 85 | /// The initializer's lifetime. Defaults to . 86 | /// A reference to this instance after the operation has completed. 87 | public static IServiceCollection AddAsyncInitializer(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]Type initializerType, ServiceLifetime lifetime = ServiceLifetime.Transient) 88 | { 89 | if (initializerType == null) 90 | throw new ArgumentNullException(nameof(initializerType)); 91 | 92 | return services 93 | .AddAsyncInitialization() 94 | .AddServiceDescriptor(ServiceDescriptor.Describe(typeof(IAsyncInitializer), initializerType, lifetime)); 95 | } 96 | 97 | /// 98 | /// Adds an async initializer whose implementation is the specified delegate. 99 | /// 100 | /// The to add the service to. 101 | /// The delegate that performs async initialization. 102 | /// A reference to this instance after the operation has completed. 103 | public static IServiceCollection AddAsyncInitializer(this IServiceCollection services, Func initializer) 104 | { 105 | if (initializer == null) 106 | throw new ArgumentNullException(nameof(initializer)); 107 | 108 | return services 109 | .AddAsyncInitialization() 110 | .AddSingleton(new DelegateAsyncInitializer(_ => initializer())); 111 | } 112 | 113 | /// 114 | /// Adds an async initializer whose implementation is the specified delegate. 115 | /// 116 | /// The to add the service to. 117 | /// The delegate that performs async initialization. 118 | /// A reference to this instance after the operation has completed. 119 | public static IServiceCollection AddAsyncInitializer(this IServiceCollection services, Func initializer) 120 | { 121 | if (initializer == null) 122 | throw new ArgumentNullException(nameof(initializer)); 123 | 124 | return services 125 | .AddAsyncInitialization() 126 | .AddSingleton(new DelegateAsyncInitializer(initializer)); 127 | } 128 | 129 | /// 130 | /// Adds an async initializer with teardown whose implementations are the specified delegates. 131 | /// 132 | /// The to add the service to. 133 | /// The delegate that performs async initialization. 134 | /// The delegate that performs async teardown. 135 | /// A reference to this instance after the operation has completed. 136 | public static IServiceCollection AddAsyncInitializer(this IServiceCollection services, Func initializer, Func teardown) 137 | { 138 | if (initializer == null) 139 | throw new ArgumentNullException(nameof(initializer)); 140 | 141 | return services 142 | .AddAsyncInitialization() 143 | .AddSingleton(new DelegateAsyncTeardown(initializer, teardown)); 144 | } 145 | 146 | // Helper to be able to use Add(ServiceDescriptor) fluently (since the return type of Add(ServiceDescriptor) is void). 147 | private static IServiceCollection AddServiceDescriptor(this IServiceCollection services, ServiceDescriptor serviceDescriptor) 148 | { 149 | services.Add(serviceDescriptor); 150 | return services; 151 | } 152 | 153 | private class DelegateAsyncInitializer : IAsyncInitializer 154 | { 155 | private readonly Func _initializer; 156 | 157 | public DelegateAsyncInitializer(Func initializer) 158 | { 159 | _initializer = initializer; 160 | } 161 | 162 | public Task InitializeAsync(CancellationToken cancellationToken) 163 | { 164 | return _initializer(cancellationToken); 165 | } 166 | } 167 | 168 | private class DelegateAsyncTeardown : IAsyncTeardown 169 | { 170 | private readonly Func _initializer; 171 | private readonly Func _teardown; 172 | 173 | public DelegateAsyncTeardown(Func initializer, Func teardown) 174 | { 175 | _initializer = initializer; 176 | _teardown = teardown; 177 | } 178 | 179 | public Task InitializeAsync(CancellationToken cancellationToken) 180 | { 181 | return _initializer(cancellationToken); 182 | } 183 | 184 | public Task TeardownAsync(CancellationToken cancellationToken) 185 | { 186 | return _teardown(cancellationToken); 187 | } 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/Extensions.Hosting.AsyncInitialization/Extensions.Hosting.AsyncInitialization.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net6.0 4 | latest 5 | enable 6 | Thomas Levesque 7 | .NET Core generic host async initialization 8 | A simple helper to perform async application initialization for the generic host in .NET 6.0 or higher. 9 | https://github.com/thomaslevesque/Extensions.Hosting.AsyncInitialization 10 | Apache-2.0 11 | .net core;hosting;async;initialization 12 | README.md 13 | https://github.com/thomaslevesque/Extensions.Hosting.AsyncInitialization 14 | $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb 15 | true 16 | 17 | 18 | 19 | bin\$(Configuration)\$(TargetFramework)\Extensions.Hosting.AsyncInitialization.xml 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | all 29 | runtime; build; native; contentfiles; analyzers 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /src/Extensions.Hosting.AsyncInitialization/Hosting/AsyncInitializationHostExtensions.cs: -------------------------------------------------------------------------------- 1 | using Extensions.Hosting.AsyncInitialization; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | // ReSharper disable once CheckNamespace 8 | namespace Microsoft.Extensions.Hosting 9 | { 10 | /// 11 | /// Provides extension methods to perform async initialization of an application. 12 | /// 13 | public static class AsyncInitializationHostExtensions 14 | { 15 | /// 16 | /// The default timeout value applied when performing teardown. 17 | /// 18 | public static readonly TimeSpan DefaultTeardownTimeout = TimeSpan.FromSeconds(10); 19 | 20 | /// 21 | /// Initializes the application, by calling all registered async initializers. 22 | /// 23 | /// The host. 24 | /// Optionally propagates notifications that the operation should be cancelled 25 | /// A that represents the initialization completion. 26 | /// Thrown when the host is null. 27 | /// Thrown when the initialization service has not been registered. 28 | /// Thrown when the cancellationToken is cancelled. 29 | public static async Task InitAsync(this IHost host, CancellationToken cancellationToken = default) 30 | { 31 | if (host == null) throw new ArgumentNullException(nameof(host)); 32 | 33 | await using var scope = host.Services.CreateAsyncScope(); 34 | var rootInitializer = scope.ServiceProvider.GetService() 35 | ?? throw new InvalidOperationException("The async initialization service isn't registered, register it by calling AddAsyncInitialization() on the service collection or by adding an async initializer."); 36 | 37 | await rootInitializer.InitializeAsync(cancellationToken).ConfigureAwait(false); 38 | } 39 | 40 | /// 41 | /// Tears down the application, by calling all registered async initializers that implement in reverse order. 42 | /// 43 | /// The host. 44 | /// Optionally propagates notifications that the operation should be cancelled 45 | /// A that represents the teardown completion. 46 | /// Thrown when the host is null. 47 | /// Thrown when the initialization service has not been registered. 48 | /// Thrown when the cancellationToken is cancelled. 49 | /// Thrown when the host instance has been disposed. 50 | /// 51 | /// Attention: This method can only be used in combination with manually calling StartAsync() and WaitForShutdownAsync() on the instance and before disposing the host. 52 | /// Calling this method after IHost.RunAsync() will throw an as the instance is disposed after running. 53 | /// 54 | public static async Task TeardownAsync(this IHost host, CancellationToken cancellationToken = default) 55 | { 56 | if (host == null) throw new ArgumentNullException(nameof(host)); 57 | 58 | await using var scope = host.Services.CreateAsyncScope(); 59 | var rootInitializer = scope.ServiceProvider.GetService() 60 | ?? throw new InvalidOperationException("The async initialization service isn't registered, register it by calling AddAsyncInitialization() on the service collection or by adding an async initializer."); 61 | 62 | await rootInitializer.TeardownAsync(cancellationToken).ConfigureAwait(false); 63 | } 64 | 65 | /// 66 | /// Initializes and runs the application, by first calling all registered async initializers. 67 | /// After the host terminates, any registered initializers that implement are called in reverse order to perform the teardown. 68 | /// The instance is disposed of after running. 69 | /// 70 | /// The to initialize and run. 71 | /// Optionally propagates notifications that the operation should be cancelled 72 | /// 73 | /// Cancelling the will not affect the teardown process. 74 | /// Teardown, when configured, is always performed, even if the process is cancelled or an exception is thrown. 75 | /// To prevent teardown from blocking forever, a with a value is passed to any registered initializers that implement . 76 | /// The entire teardown process will be cancelled if the timeout expires before all initializers have completed teardown. 77 | /// 78 | /// The that represents the asynchronous operation. 79 | /// Thrown when the host is null. 80 | /// Thrown when the initialization service has not been registered. 81 | /// Thrown when the cancellationToken is cancelled. 82 | /// Thrown when teardown times out. 83 | /// Thrown when multiple exceptions occur. 84 | public static async Task InitAndRunAsync(this IHost host, CancellationToken cancellationToken = default) 85 | => await host.InitAndRunAsync(DefaultTeardownTimeout, cancellationToken).ConfigureAwait(false); 86 | 87 | 88 | #pragma warning disable 1573 89 | /// 90 | /// The timeout value to use for teardown. Setting this value to will disable timeout handling. 91 | /// 92 | /// Cancelling the will not affect the teardown process. 93 | /// Teardown, when configured, is always performed, even if the process is cancelled or an exception is thrown, using a timeout as specified by the parameter. 94 | /// The entire teardown process will be cancelled if the timeout expires before all initializers have completed teardown. 95 | /// 96 | /// Thrown when an invalid value is passed. 97 | public static async Task InitAndRunAsync(this IHost host, TimeSpan teardownTimeout, CancellationToken cancellationToken = default) 98 | { 99 | if (host == null) throw new ArgumentNullException(nameof(host)); 100 | 101 | await using (host.AsAsyncDisposable().ConfigureAwait(false)) 102 | { 103 | cancellationToken.ThrowIfCancellationRequested(); 104 | 105 | using var cts = new CancellationTokenSource(); 106 | Exception? innerException = null; 107 | try 108 | { 109 | try 110 | { 111 | await host.InitAsync(cancellationToken).ConfigureAwait(false); 112 | await host.StartAsync(cancellationToken).ConfigureAwait(false); 113 | await host.WaitForShutdownAsync(cancellationToken).ConfigureAwait(false); 114 | } 115 | catch (Exception ex) 116 | { 117 | innerException = ex; 118 | throw; 119 | } 120 | finally 121 | { 122 | cts.CancelAfter(teardownTimeout); 123 | await host.TeardownAsync(cts.Token).WaitAsync(cts.Token).ConfigureAwait(false); 124 | } 125 | } 126 | catch (OperationCanceledException) when (cts.IsCancellationRequested) 127 | { 128 | var timeoutException = new TimeoutException("Teardown cancelled due to timeout."); 129 | if (innerException != null) 130 | { 131 | throw new AggregateException(innerException, timeoutException); 132 | } 133 | throw timeoutException; 134 | } 135 | } 136 | } 137 | #pragma warning restore 1573 138 | 139 | // wraps an IHost instance in an IAsyncDisposable 140 | private static IAsyncDisposable AsAsyncDisposable(this IHost host) 141 | { 142 | return host as IAsyncDisposable ?? new AsyncDisposableHostWrapper(host); 143 | } 144 | 145 | // IAsyncDisposable wrapper for IHost 146 | private class AsyncDisposableHostWrapper : IAsyncDisposable 147 | { 148 | private readonly IHost _host; 149 | public AsyncDisposableHostWrapper(IHost host) 150 | { 151 | _host = host ?? throw new ArgumentNullException(nameof(host)); 152 | } 153 | public ValueTask DisposeAsync() 154 | { 155 | if (_host is IAsyncDisposable asyncDisposable) 156 | { 157 | return asyncDisposable.DisposeAsync(); 158 | } 159 | _host.Dispose(); 160 | return ValueTask.CompletedTask; 161 | } 162 | } 163 | } 164 | } -------------------------------------------------------------------------------- /src/Extensions.Hosting.AsyncInitialization/IAsyncInitializer.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | 4 | namespace Extensions.Hosting.AsyncInitialization 5 | { 6 | /// 7 | /// Represents a type that performs async initialization. 8 | /// 9 | public interface IAsyncInitializer 10 | { 11 | /// 12 | /// Performs async initialization. 13 | /// 14 | /// Notifies that the operation should be cancelled 15 | /// A task that represents the initialization completion. 16 | Task InitializeAsync(CancellationToken cancellationToken); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Extensions.Hosting.AsyncInitialization/IAsyncTeardown.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using System.Threading; 3 | 4 | namespace Extensions.Hosting.AsyncInitialization 5 | { 6 | /// 7 | /// Represents a type that performs async teardown for types implementing 8 | /// 9 | public interface IAsyncTeardown : IAsyncInitializer 10 | { 11 | /// 12 | /// Performs async teardown. 13 | /// 14 | /// Notifies that the operation should be cancelled 15 | /// A task that represents the teardown completion. 16 | Task TeardownAsync(CancellationToken cancellationToken); 17 | } 18 | } -------------------------------------------------------------------------------- /src/Extensions.Hosting.AsyncInitialization/RootInitializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace Extensions.Hosting.AsyncInitialization 9 | { 10 | internal class RootInitializer 11 | { 12 | private readonly ILogger _logger; 13 | private readonly IEnumerable _initializers; 14 | 15 | public RootInitializer(ILogger logger, IEnumerable initializers) 16 | { 17 | _logger = logger; 18 | _initializers = initializers; 19 | } 20 | 21 | public async Task InitializeAsync(CancellationToken cancellationToken = default) 22 | { 23 | _logger.LogInformation("Starting async initialization"); 24 | 25 | try 26 | { 27 | foreach (var initializer in _initializers) 28 | { 29 | cancellationToken.ThrowIfCancellationRequested(); 30 | _logger.LogInformation("Starting async initialization for {InitializerType}", initializer.GetType()); 31 | try 32 | { 33 | await initializer.InitializeAsync(cancellationToken); 34 | _logger.LogInformation("Async initialization for {InitializerType} completed", initializer.GetType()); 35 | } 36 | catch (Exception ex) 37 | { 38 | _logger.LogError(ex, "Async initialization for {InitializerType} failed", initializer.GetType()); 39 | throw; 40 | } 41 | } 42 | 43 | _logger.LogInformation("Async initialization completed"); 44 | } 45 | catch (OperationCanceledException) 46 | { 47 | _logger.LogWarning("Async initialization cancelled"); 48 | throw; 49 | } 50 | catch (Exception ex) 51 | { 52 | _logger.LogError(ex, "Async initialization failed"); 53 | throw; 54 | } 55 | } 56 | 57 | public async Task TeardownAsync(CancellationToken cancellationToken = default) 58 | { 59 | _logger.LogInformation("Starting async teardown"); 60 | 61 | try 62 | { 63 | foreach (var initializer in _initializers.Reverse().OfType()) 64 | { 65 | cancellationToken.ThrowIfCancellationRequested(); 66 | _logger.LogDebug("Starting async teardown for {InitializerType}", initializer.GetType()); 67 | try 68 | { 69 | await initializer.TeardownAsync(cancellationToken); 70 | _logger.LogDebug("Async teardown for {InitializerType} completed", initializer.GetType()); 71 | } 72 | catch (Exception ex) 73 | { 74 | _logger.LogError(ex, "Async teardown for {InitializerType} failed", initializer.GetType()); 75 | throw; 76 | } 77 | } 78 | 79 | _logger.LogInformation("Async teardown completed"); 80 | } 81 | catch (OperationCanceledException) 82 | { 83 | _logger.LogWarning("Async teardown cancelled"); 84 | throw; 85 | } 86 | catch (Exception ex) 87 | { 88 | _logger.LogError(ex, "Async teardown failed"); 89 | throw; 90 | } 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /tests/Extensions.Hosting.AsyncInitialization.Tests/AsyncInitializationAndRunTests.cs: -------------------------------------------------------------------------------- 1 | using FakeItEasy; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Hosting; 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | using Xunit.Abstractions; 9 | using static Extensions.Hosting.AsyncInitialization.Tests.CommonTestTypes; 10 | 11 | namespace Extensions.Hosting.AsyncInitialization.Tests 12 | { 13 | public class AsyncInitializationAndRunTests 14 | { 15 | public AsyncInitializationAndRunTests(ITestOutputHelper testOutput) 16 | { 17 | OutputHelper = testOutput; 18 | } 19 | 20 | private ITestOutputHelper OutputHelper { get; } 21 | 22 | [Fact] 23 | public async Task InitAndRunAsync_throws_InvalidOperationException_when_services_are_not_registered() 24 | { 25 | var host = CommonTestTypes.CreateHost(services => { }); 26 | var exception = await Record.ExceptionAsync(() => host.InitAsync()); 27 | Assert.IsType(exception); 28 | Assert.Equal("The async initialization service isn't registered, register it by calling AddAsyncInitialization() on the service collection or by adding an async initializer.", exception.Message); 29 | } 30 | 31 | 32 | 33 | [Fact] 34 | public async Task Multiple_initializers_with_teardown_are_called_in_correct_order() 35 | { 36 | var initializer1 = A.Fake(); 37 | var initializer2 = A.Fake(); 38 | var initializer3 = A.Fake(); 39 | 40 | var host = CreateHost(services => 41 | { 42 | services.AddAsyncInitializer(initializer1); 43 | services.AddAsyncInitializer(initializer2); 44 | services.AddAsyncInitializer(initializer3); 45 | services.AddHostedService(); 46 | }); 47 | 48 | await host.InitAndRunAsync(); 49 | 50 | A.CallTo(() => initializer1.InitializeAsync(A._)).MustHaveHappenedOnceExactly() 51 | .Then(A.CallTo(() => initializer2.InitializeAsync(A._)).MustHaveHappenedOnceExactly()) 52 | .Then(A.CallTo(() => initializer3.InitializeAsync(A._)).MustHaveHappenedOnceExactly()) 53 | .Then(A.CallTo(() => initializer3.TeardownAsync(A._)).MustHaveHappenedOnceExactly()) 54 | .Then(A.CallTo(() => initializer2.TeardownAsync(A._)).MustHaveHappenedOnceExactly()) 55 | .Then(A.CallTo(() => initializer1.TeardownAsync(A._)).MustHaveHappenedOnceExactly()); 56 | } 57 | 58 | [Fact] 59 | public async Task Cancelled_initializer_skips_host_run_and_calls_teardown() 60 | { 61 | using var cancellationTokenSource = new CancellationTokenSource(); 62 | var initializer1 = A.Fake(); 63 | var initializer2 = A.Fake(); 64 | var initializer3 = A.Fake(); 65 | var service = A.Fake(); 66 | 67 | A.CallTo(() => initializer1.InitializeAsync(A._)).Invokes(_ => cancellationTokenSource.Cancel()); 68 | 69 | var host = CreateHost(services => 70 | { 71 | services.AddAsyncInitializer(initializer1); 72 | services.AddAsyncInitializer(initializer2); 73 | services.AddAsyncInitializer(initializer3); 74 | services.AddHostedService(factory => service); 75 | }); 76 | 77 | await Assert.ThrowsAsync(() => host.InitAndRunAsync(cancellationTokenSource.Token)); 78 | 79 | A.CallTo(() => initializer1.InitializeAsync(A._)).MustHaveHappenedOnceExactly(); 80 | A.CallTo(() => initializer2.InitializeAsync(A._)).MustNotHaveHappened(); 81 | A.CallTo(() => initializer3.InitializeAsync(A._)).MustNotHaveHappened(); 82 | A.CallTo(() => initializer1.TeardownAsync(A._)).MustHaveHappenedOnceExactly(); 83 | A.CallTo(() => initializer2.TeardownAsync(A._)).MustHaveHappenedOnceExactly(); 84 | A.CallTo(() => initializer3.TeardownAsync(A._)).MustHaveHappenedOnceExactly(); 85 | A.CallTo(() => service.StartAsync(A._)).MustNotHaveHappened(); 86 | } 87 | 88 | [Fact] 89 | public async Task Failing_initializer_skips_host_run_and_calls_teardown() 90 | { 91 | var service = A.Fake(); 92 | var initializer = A.Fake(); 93 | A.CallTo(() => initializer.InitializeAsync(A._)).ThrowsAsync(() => new Exception("oops")); 94 | 95 | var host = CreateHost(services => 96 | { 97 | services.AddAsyncInitializer(initializer); 98 | services.AddHostedService(factory => service); 99 | }); 100 | 101 | var exception = await Record.ExceptionAsync(() => host.InitAndRunAsync()); 102 | Assert.IsType(exception); 103 | Assert.Equal("oops", exception.Message); 104 | 105 | A.CallTo(() => initializer.InitializeAsync(A._)).MustHaveHappenedOnceExactly(); 106 | A.CallTo(() => service.StartAsync(A._)).MustNotHaveHappened(); 107 | A.CallTo(() => initializer.TeardownAsync(A._)).MustHaveHappenedOnceExactly(); 108 | } 109 | 110 | [Theory] 111 | [InlineData(false)] 112 | [InlineData(true)] 113 | public async Task Host_is_disposed_after_successful_run(bool forceIDisposableHost) 114 | { 115 | var host = CreateHost(services => 116 | { 117 | services.AddAsyncInitializer(sp => A.Fake()); 118 | services.AddHostedService(); 119 | }, forceIDisposableHost: forceIDisposableHost); 120 | 121 | OutputHelper.WriteLine(host is IAsyncDisposable ? "Using IAsyncDisposable Host" : "Using IDisposable Host"); 122 | 123 | await host.InitAndRunAsync(); 124 | Assert.Throws(host.Services.CreateScope); 125 | 126 | } 127 | 128 | [Theory] 129 | [InlineData(false)] 130 | [InlineData(true)] 131 | public async Task Host_is_disposed_after_failing_teardown(bool forceIDisposableHost) 132 | { 133 | var initializer = A.Fake(); 134 | A.CallTo(() => initializer.TeardownAsync(A._)).ThrowsAsync(() => new Exception("oops")); 135 | 136 | var host = CreateHost(services => 137 | { 138 | services.AddAsyncInitializer(initializer); 139 | services.AddHostedService(); 140 | }, forceIDisposableHost: forceIDisposableHost); 141 | 142 | OutputHelper.WriteLine(host is IAsyncDisposable ? "Using IAsyncDisposable Host" : "Using IDisposable Host"); 143 | 144 | var exception = await Record.ExceptionAsync(() => host.InitAndRunAsync()); 145 | Assert.IsType(exception); 146 | Assert.Equal("oops", exception.Message); 147 | 148 | Assert.Throws(host.Services.CreateScope); 149 | } 150 | 151 | [Theory] 152 | [InlineData(false, false)] 153 | [InlineData(true, false)] 154 | [InlineData(false, true)] 155 | [InlineData(true, true)] 156 | public async Task Host_is_disposed_after_teardown_timeout(bool forceIDisposableHost, bool supportsCancellation) 157 | { 158 | var timeout = TimeSpan.FromMilliseconds(100); 159 | 160 | var host = CreateHost(services => 161 | { 162 | services.AddAsyncInitializer(sp => new EndlessTeardownInitializer(supportsCancellation)); 163 | services.AddHostedService(); 164 | }, forceIDisposableHost: forceIDisposableHost); 165 | 166 | OutputHelper.WriteLine(host is IAsyncDisposable ? "Using IAsyncDisposable Host" : "Using IDisposable Host"); 167 | 168 | await Assert.ThrowsAnyAsync(() => host.InitAndRunAsync(timeout)); 169 | 170 | Assert.Throws(host.Services.CreateScope); 171 | } 172 | 173 | [Theory] 174 | [InlineData(false)] 175 | [InlineData(true)] 176 | public async Task InitAndRunAsync_throws_TimeoutException_when_teardown_exceeds_timeout(bool supportsCancellation) 177 | { 178 | var timeout = TimeSpan.FromMilliseconds(100); 179 | 180 | var host = CreateHost(services => 181 | { 182 | services.AddAsyncInitializer(sp => new EndlessTeardownInitializer(supportsCancellation)); 183 | services.AddHostedService(); 184 | }); 185 | 186 | await Assert.ThrowsAsync(() => host.InitAndRunAsync(timeout)); 187 | } 188 | 189 | [Theory] 190 | [InlineData(false)] 191 | [InlineData(true)] 192 | public async Task InitAndRunAsync_throws_AggregateException_when_host_fails_and_teardown_exceeds_timeout(bool supportsCancellation) 193 | { 194 | var timeout = TimeSpan.FromMilliseconds(100); 195 | 196 | var host = CreateHost(services => 197 | { 198 | services.AddAsyncInitializer(sp => new EndlessTeardownInitializer(supportsCancellation)); 199 | services.AddHostedService(); 200 | }); 201 | 202 | var exception = await Record.ExceptionAsync(() => host.InitAndRunAsync(timeout)); 203 | Assert.IsType(exception); 204 | var innerExceptions = ((AggregateException)exception).InnerExceptions; 205 | Assert.Collection(innerExceptions, 206 | item => Assert.IsType(item), 207 | item => Assert.IsType(item)); 208 | } 209 | 210 | [Theory] 211 | [InlineData(false)] 212 | [InlineData(true)] 213 | 214 | public async Task Host_is_disposed_with_infinite_teardown_timeout(bool forceIDisposableHost) 215 | { 216 | var timeout = Timeout.InfiniteTimeSpan; 217 | 218 | var host = CreateHost(services => 219 | { 220 | services.AddAsyncInitializer(sp => A.Fake()); 221 | services.AddHostedService(); 222 | }, forceIDisposableHost: forceIDisposableHost); 223 | 224 | OutputHelper.WriteLine(host is IAsyncDisposable ? "Using IAsyncDisposable Host" : "Using IDisposable Host"); 225 | 226 | await host.InitAndRunAsync(timeout); 227 | 228 | Assert.Throws(host.Services.CreateScope); 229 | } 230 | 231 | 232 | [Theory] 233 | [InlineData(false)] 234 | [InlineData(true)] 235 | public async Task Host_is_disposed_after_failing_initializer(bool forceIDisposableHost) 236 | { 237 | var initializer = A.Fake(); 238 | A.CallTo(() => initializer.InitializeAsync(default)).ThrowsAsync(() => new Exception("oops")); 239 | 240 | var host = CreateHost(services => 241 | { 242 | services.AddAsyncInitializer(initializer); 243 | services.AddHostedService(); 244 | }, forceIDisposableHost: forceIDisposableHost); 245 | 246 | OutputHelper.WriteLine(host is IAsyncDisposable ? "Using IAsyncDisposable Host" : "Using IDisposable Host"); 247 | 248 | var exception = await Record.ExceptionAsync(() => host.InitAndRunAsync()); 249 | Assert.IsType(exception); 250 | Assert.Equal("oops", exception.Message); 251 | 252 | Assert.Throws(host.Services.CreateScope); 253 | } 254 | 255 | [Theory] 256 | [InlineData(false)] 257 | [InlineData(true)] 258 | public async Task Host_is_disposed_after_cancellation(bool forceIDisposableHost) 259 | { 260 | var host = CreateHost(services => 261 | { 262 | services.AddAsyncInitializer(sp => A.Fake()); 263 | services.AddHostedService(); 264 | }, forceIDisposableHost: forceIDisposableHost); 265 | 266 | OutputHelper.WriteLine(host is IAsyncDisposable ? "Using IAsyncDisposable Host" : "Using IDisposable Host"); 267 | 268 | var lifetime = host.Services.GetRequiredService(); 269 | using var cancellationTokenSource = new CancellationTokenSource(); 270 | using var ctr = lifetime.ApplicationStarted.Register(cancellationTokenSource.Cancel); 271 | 272 | await host.InitAndRunAsync(cancellationTokenSource.Token); 273 | 274 | Assert.Throws(host.Services.CreateScope); 275 | } 276 | 277 | [Theory] 278 | [InlineData(false)] 279 | [InlineData(true)] 280 | public async Task Host_is_disposed_after_service_fails(bool forceIDisposableHost) 281 | { 282 | var host = CreateHost(services => 283 | { 284 | services.AddAsyncInitializer(sp => A.Fake()); 285 | services.AddHostedService(); 286 | }, forceIDisposableHost: forceIDisposableHost); 287 | 288 | OutputHelper.WriteLine(host is IAsyncDisposable ? "Using IAsyncDisposable Host" : "Using IDisposable Host"); 289 | 290 | await Assert.ThrowsAsync(() => host.InitAndRunAsync()); 291 | Assert.Throws(host.Services.CreateScope); 292 | } 293 | 294 | 295 | [Fact] 296 | public async Task Initializer_with_teardown_and_scoped_dependency_is_resolved() 297 | { 298 | 299 | var host = CreateHost( 300 | services => 301 | { 302 | services.AddScoped(sp => A.Fake()); 303 | services.AddAsyncInitializer(); 304 | services.AddHostedService(); 305 | }, 306 | true); 307 | 308 | await host.InitAndRunAsync(); 309 | } 310 | 311 | 312 | [Fact] 313 | public async Task Single_initializer_with_teardown_is_called() 314 | { 315 | var initializer = A.Fake(); 316 | 317 | var host = CreateHost(services => 318 | { 319 | services.AddAsyncInitializer(initializer); 320 | services.AddHostedService(); 321 | }); 322 | 323 | await host.InitAndRunAsync(); 324 | 325 | A.CallTo(() => initializer.InitializeAsync(A._)).MustHaveHappenedOnceExactly(); 326 | A.CallTo(() => initializer.TeardownAsync(A._)).MustHaveHappenedOnceExactly(); 327 | } 328 | 329 | [Fact] 330 | public async Task InitAndRunAsync_throws_OperationCancelledException_when_called_with_cancelled_token() 331 | { 332 | var initializer = A.Fake(); 333 | var service = A.Fake(); 334 | 335 | var host = CreateHost(services => 336 | { 337 | services.AddAsyncInitializer(initializer); 338 | services.AddHostedService(factory => service); 339 | }); 340 | 341 | await Assert.ThrowsAsync(() => host.InitAndRunAsync(new CancellationToken(true))); 342 | 343 | A.CallTo(() => initializer.InitializeAsync(A._)).MustNotHaveHappened(); 344 | A.CallTo(() => initializer.TeardownAsync(A._)).MustNotHaveHappened(); 345 | A.CallTo(() => service.StartAsync(A._)).MustNotHaveHappened(); 346 | } 347 | 348 | [Fact] 349 | public async Task InitAndRunAsync_without_initializer_does_not_fail() 350 | { 351 | var host = CreateHost(services => 352 | { 353 | services.AddAsyncInitialization(); 354 | services.AddHostedService(); 355 | }); 356 | 357 | await host.InitAndRunAsync(); 358 | } 359 | } 360 | } 361 | -------------------------------------------------------------------------------- /tests/Extensions.Hosting.AsyncInitialization.Tests/AsyncInitializationTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using FakeItEasy; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using Xunit; 8 | using static Extensions.Hosting.AsyncInitialization.Tests.CommonTestTypes; 9 | 10 | namespace Extensions.Hosting.AsyncInitialization.Tests 11 | { 12 | public class AsyncInitializationTests 13 | { 14 | [Fact] 15 | public async Task Single_initializer_is_called() 16 | { 17 | var initializer = A.Fake(); 18 | 19 | var host = CreateHost(services => services.AddAsyncInitializer(initializer)); 20 | 21 | await host.InitAsync(); 22 | 23 | A.CallTo(() => initializer.InitializeAsync(CancellationToken.None)).MustHaveHappenedOnceExactly(); 24 | } 25 | 26 | [Fact] 27 | public async Task Delegate_initializer_is_called() 28 | { 29 | var initializer = A.Fake>(); 30 | 31 | var host = CreateHost(services => services.AddAsyncInitializer(initializer)); 32 | 33 | await host.InitAsync(); 34 | 35 | A.CallTo(() => initializer(CancellationToken.None)).MustHaveHappenedOnceExactly(); 36 | } 37 | 38 | [Fact] 39 | public async Task Multiple_initializers_are_called_in_order() 40 | { 41 | var initializer1 = A.Fake(); 42 | var initializer2 = A.Fake(); 43 | var initializer3 = A.Fake(); 44 | 45 | var host = CreateHost(services => 46 | { 47 | services.AddAsyncInitializer(initializer1); 48 | services.AddAsyncInitializer(initializer2); 49 | services.AddAsyncInitializer(initializer3); 50 | }); 51 | 52 | await host.InitAsync(); 53 | 54 | A.CallTo(() => initializer1.InitializeAsync(default)).MustHaveHappenedOnceExactly() 55 | .Then(A.CallTo(() => initializer2.InitializeAsync(default)).MustHaveHappenedOnceExactly()) 56 | .Then(A.CallTo(() => initializer3.InitializeAsync(default)).MustHaveHappenedOnceExactly()); 57 | } 58 | 59 | [Fact] 60 | public async Task Initializer_with_scoped_dependency_is_resolved() 61 | { 62 | var host = CreateHost( 63 | services => 64 | { 65 | services.AddScoped(sp => A.Fake()); 66 | services.AddAsyncInitializer(); 67 | }, 68 | true); 69 | 70 | await host.InitAsync(); 71 | } 72 | 73 | [Fact] 74 | public async Task Failing_initializer_makes_initialization_fail() 75 | { 76 | var initializer1 = A.Fake(); 77 | var initializer2 = A.Fake(); 78 | var initializer3 = A.Fake(); 79 | 80 | A.CallTo(() => initializer2.InitializeAsync(default)).ThrowsAsync(() => new Exception("oops")); 81 | 82 | var host = CreateHost(services => 83 | { 84 | services.AddAsyncInitializer(initializer1); 85 | services.AddAsyncInitializer(initializer2); 86 | services.AddAsyncInitializer(initializer3); 87 | }); 88 | 89 | var exception = await Record.ExceptionAsync(() => host.InitAsync()); 90 | Assert.IsType(exception); 91 | Assert.Equal("oops", exception.Message); 92 | 93 | A.CallTo(() => initializer1.InitializeAsync(default)).MustHaveHappenedOnceExactly(); 94 | A.CallTo(() => initializer3.InitializeAsync(default)).MustNotHaveHappened(); 95 | } 96 | 97 | [Fact] 98 | public async Task Cancelled_initializer_makes_initialization_fail() 99 | { 100 | using var cancellationTokenSource = new CancellationTokenSource(); 101 | var initializer1 = A.Fake(); 102 | var initializer2 = A.Fake(); 103 | var initializer3 = A.Fake(); 104 | 105 | 106 | A.CallTo(() => initializer1.InitializeAsync(A._)).Invokes(_ => cancellationTokenSource.Cancel()); 107 | 108 | var host = CreateHost(services => 109 | { 110 | services.AddAsyncInitializer(initializer1); 111 | services.AddAsyncInitializer(initializer2); 112 | services.AddAsyncInitializer(initializer3); 113 | }); 114 | 115 | var exception = await Record.ExceptionAsync(() => host.InitAsync(cancellationTokenSource.Token)); 116 | Assert.IsType(exception); 117 | 118 | A.CallTo(() => initializer1.InitializeAsync(A._)).MustHaveHappenedOnceExactly(); 119 | A.CallTo(() => initializer2.InitializeAsync(A._)).MustNotHaveHappened(); 120 | A.CallTo(() => initializer3.InitializeAsync(A._)).MustNotHaveHappened(); 121 | } 122 | 123 | [Fact] 124 | public async Task InitAsync_throws_InvalidOperationException_when_services_are_not_registered() 125 | { 126 | var host = CreateHost(services => { }); 127 | var exception = await Record.ExceptionAsync(() => host.InitAsync()); 128 | Assert.IsType(exception); 129 | Assert.Equal("The async initialization service isn't registered, register it by calling AddAsyncInitialization() on the service collection or by adding an async initializer.", exception.Message); 130 | } 131 | } 132 | } -------------------------------------------------------------------------------- /tests/Extensions.Hosting.AsyncInitialization.Tests/AsyncTeardownTests.cs: -------------------------------------------------------------------------------- 1 | using FakeItEasy; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Hosting; 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | using static Extensions.Hosting.AsyncInitialization.Tests.CommonTestTypes; 9 | 10 | namespace Extensions.Hosting.AsyncInitialization.Tests 11 | { 12 | public class AsyncTeardownTests 13 | { 14 | [Fact] 15 | public async Task Single_teardown_is_called() 16 | { 17 | var initializer = A.Fake(); 18 | 19 | var host = CreateHost(services => services.AddAsyncInitializer(initializer)); 20 | 21 | await host.TeardownAsync(); 22 | 23 | A.CallTo(() => initializer.TeardownAsync(CancellationToken.None)).MustHaveHappenedOnceExactly(); 24 | } 25 | 26 | [Fact] 27 | public async Task Multiple_teardown_are_called_in_reverse_order() 28 | { 29 | var initializer1 = A.Fake(); 30 | var initializer2 = A.Fake(); 31 | var initializer3 = A.Fake(); 32 | 33 | var host = CreateHost(services => 34 | { 35 | services.AddAsyncInitializer(initializer1); 36 | services.AddAsyncInitializer(initializer2); 37 | services.AddAsyncInitializer(initializer3); 38 | }); 39 | 40 | await host.TeardownAsync(); 41 | 42 | A.CallTo(() => initializer3.TeardownAsync(default)).MustHaveHappenedOnceExactly() 43 | .Then(A.CallTo(() => initializer2.TeardownAsync(default)).MustHaveHappenedOnceExactly()) 44 | .Then(A.CallTo(() => initializer1.TeardownAsync(default)).MustHaveHappenedOnceExactly()); 45 | } 46 | 47 | [Fact] 48 | public async Task TeardownAsync_throws_InvalidOperationException_when_services_are_not_registered() 49 | { 50 | var host = CommonTestTypes.CreateHost(services => { }); 51 | var exception = await Record.ExceptionAsync(() => host.TeardownAsync()); 52 | Assert.IsType(exception); 53 | Assert.Equal("The async initialization service isn't registered, register it by calling AddAsyncInitialization() on the service collection or by adding an async initializer.", exception.Message); 54 | } 55 | 56 | [Fact] 57 | public async Task TeardownAsync_throws_ObjectDisposedException_when_called_after_RunAsync() 58 | { 59 | var host = CreateHost(services => 60 | { 61 | services.AddAsyncInitializer(factory => A.Fake()); 62 | }); 63 | 64 | await Assert.ThrowsAsync(() => host.RunAsync(new CancellationToken(true))); 65 | await Assert.ThrowsAsync(() => host.TeardownAsync()); 66 | 67 | } 68 | 69 | 70 | 71 | [Fact] 72 | public async Task Delegate_teardown_is_called() 73 | { 74 | var initializer = A.Fake>(); 75 | var teardown = A.Fake>(); 76 | 77 | var host = CreateHost(services => services.AddAsyncInitializer(initializer, teardown)); 78 | 79 | await host.TeardownAsync(); 80 | 81 | A.CallTo(() => initializer(CancellationToken.None)).MustNotHaveHappened(); 82 | A.CallTo(() => teardown(CancellationToken.None)).MustHaveHappenedOnceExactly(); 83 | } 84 | 85 | [Fact] 86 | public async Task Failing_teardown_makes_teardown_fail() 87 | { 88 | var initializer1 = A.Fake(); 89 | var initializer2 = A.Fake(); 90 | var initializer3 = A.Fake(); 91 | 92 | A.CallTo(() => initializer2.TeardownAsync(default)).ThrowsAsync(() => new Exception("oops")); 93 | 94 | var host = CreateHost(services => 95 | { 96 | services.AddAsyncInitializer(initializer1); 97 | services.AddAsyncInitializer(initializer2); 98 | services.AddAsyncInitializer(initializer3); 99 | }); 100 | 101 | var exception = await Record.ExceptionAsync(() => host.TeardownAsync()); 102 | Assert.IsType(exception); 103 | Assert.Equal("oops", exception.Message); 104 | 105 | A.CallTo(() => initializer3.TeardownAsync(default)).MustHaveHappenedOnceExactly(); 106 | A.CallTo(() => initializer1.TeardownAsync(default)).MustNotHaveHappened(); 107 | } 108 | 109 | [Fact] 110 | public async Task Teardown_with_scoped_dependency_is_resolved() 111 | { 112 | var host = CreateHost( 113 | services => 114 | { 115 | services.AddScoped(sp => A.Fake()); 116 | services.AddAsyncInitializer(); 117 | }, 118 | true); 119 | 120 | await host.TeardownAsync(); 121 | } 122 | 123 | [Fact] 124 | public async Task Cancelled_Teardown_makes_teardown_fail() 125 | { 126 | using var cancellationTokenSource = new CancellationTokenSource(); 127 | var initializer1 = A.Fake(); 128 | var initializer2 = A.Fake(); 129 | var initializer3 = A.Fake(); 130 | 131 | 132 | A.CallTo(() => initializer3.TeardownAsync(A._)).Invokes(_ => cancellationTokenSource.Cancel()); 133 | 134 | var host = CreateHost(services => 135 | { 136 | services.AddAsyncInitializer(initializer1); 137 | services.AddAsyncInitializer(initializer2); 138 | services.AddAsyncInitializer(initializer3); 139 | }); 140 | 141 | var exception = await Record.ExceptionAsync(() => host.TeardownAsync(cancellationTokenSource.Token)); 142 | Assert.IsType(exception); 143 | 144 | A.CallTo(() => initializer3.TeardownAsync(A._)).MustHaveHappenedOnceExactly(); 145 | A.CallTo(() => initializer2.TeardownAsync(A._)).MustNotHaveHappened(); 146 | A.CallTo(() => initializer1.TeardownAsync(A._)).MustNotHaveHappened(); 147 | } 148 | 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /tests/Extensions.Hosting.AsyncInitialization.Tests/CommonTestTypes.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using System; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Extensions.Hosting.AsyncInitialization.Tests 8 | { 9 | public class CommonTestTypes 10 | { 11 | public interface IDependency {} 12 | 13 | public class Dependency : IDependency { } 14 | 15 | public interface IDisposableDependency : IDependency, IDisposable {} 16 | 17 | public class DisposableDependency : IDisposableDependency 18 | { 19 | public void Dispose() {} 20 | } 21 | 22 | 23 | public class Initializer : IAsyncInitializer 24 | { 25 | // ReSharper disable once NotAccessedField.Local 26 | private readonly IDependency _dependency; 27 | 28 | public Initializer(IDependency dependency) 29 | { 30 | _dependency = dependency; 31 | } 32 | 33 | public Task InitializeAsync(CancellationToken cancellationToken) => Task.CompletedTask; 34 | } 35 | 36 | public class InitializerWithTearDown : IAsyncTeardown 37 | { 38 | // ReSharper disable once NotAccessedField.Local 39 | private readonly IDependency _dependency; 40 | 41 | public InitializerWithTearDown(IDependency dependency) 42 | { 43 | _dependency = dependency; 44 | } 45 | 46 | public Task InitializeAsync(CancellationToken cancellationToken) => Task.CompletedTask; 47 | 48 | public Task TeardownAsync(CancellationToken cancellationToken) => Task.CompletedTask; 49 | } 50 | 51 | public class EndlessTeardownInitializer : IAsyncTeardown 52 | { 53 | private bool _supportsCancellation; 54 | public EndlessTeardownInitializer(bool supportsCancellation = true) 55 | { 56 | _supportsCancellation = supportsCancellation; 57 | } 58 | public Task InitializeAsync(CancellationToken cancellationToken) => Task.CompletedTask; 59 | 60 | public Task TeardownAsync(CancellationToken cancellationToken) 61 | { 62 | return _supportsCancellation ? Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken) : Task.Delay(Timeout.InfiniteTimeSpan); 63 | } 64 | } 65 | 66 | public class TestService : BackgroundService 67 | { 68 | protected override Task ExecuteAsync(CancellationToken stoppingToken) => Task.CompletedTask; 69 | } 70 | 71 | public class FaultingService : BackgroundService 72 | { 73 | protected override Task ExecuteAsync(CancellationToken stoppingToken) => throw new ApplicationException(nameof(FaultingService)); 74 | } 75 | 76 | public class StoppingService : BackgroundService 77 | { 78 | private readonly IHostApplicationLifetime _lifetime; 79 | public StoppingService(IHostApplicationLifetime lifetime) 80 | { 81 | _lifetime = lifetime; 82 | } 83 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 84 | { 85 | _lifetime.StopApplication(); 86 | return Task.CompletedTask; 87 | } 88 | } 89 | 90 | 91 | 92 | public class SyncDisposableHostWrapper : IHost, IDisposable 93 | { 94 | private readonly IHost _host; 95 | public SyncDisposableHostWrapper(IHost host) 96 | { 97 | _host = host ?? throw new ArgumentNullException(nameof(host)); 98 | } 99 | 100 | public IServiceProvider Services => _host.Services; 101 | 102 | public void Dispose() 103 | { 104 | _host.Dispose(); 105 | } 106 | 107 | public Task StartAsync(CancellationToken cancellationToken = default) 108 | { 109 | return _host.StartAsync(cancellationToken); 110 | } 111 | 112 | public Task StopAsync(CancellationToken cancellationToken = default) 113 | { 114 | return _host.StopAsync(cancellationToken); 115 | } 116 | } 117 | 118 | public static IHost CreateHost(Action configureServices, bool validateScopes = false, bool forceIDisposableHost = false) 119 | { 120 | var host = new HostBuilder() 121 | .ConfigureServices(configureServices) 122 | .UseServiceProviderFactory(new DefaultServiceProviderFactory( 123 | new ServiceProviderOptions 124 | { 125 | ValidateScopes = validateScopes 126 | } 127 | )) 128 | .Build(); 129 | 130 | return forceIDisposableHost ? new SyncDisposableHostWrapper(host) : host; 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /tests/Extensions.Hosting.AsyncInitialization.Tests/Extensions.Hosting.AsyncInitialization.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net6.0;net8.0 4 | latest 5 | enable 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | all 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /tools/build/Build.cs: -------------------------------------------------------------------------------- 1 | // using System.IO; 2 | // using System.Runtime.CompilerServices; 3 | // using System.Threading.Tasks; 4 | // using McMaster.Extensions.CommandLineUtils; 5 | // using static Bullseye.Targets; 6 | // using static SimpleExec.Command; 7 | // 8 | // namespace build 9 | // { 10 | // [Command(UnrecognizedArgumentHandling = UnrecognizedArgumentHandling.CollectAndContinue)] 11 | // [SuppressDefaultHelpOption] 12 | // class Build 13 | // { 14 | // static void Main(string[] args) => 15 | // CommandLineApplication.Execute(args); 16 | // 17 | // [Option("-h|-?|--help", "Show help message", CommandOptionType.NoValue)] 18 | // public bool ShowHelp { get; } = false; 19 | // 20 | // [Option("-c|--configuration", "The configuration to build", CommandOptionType.SingleValue)] 21 | // public string Configuration { get; } = "Release"; 22 | // 23 | // public string[] RemainingArguments { get; } = null; 24 | // 25 | // public async Task OnExecuteAsync(CommandLineApplication app) 26 | // { 27 | // Directory.SetCurrentDirectory(GetSolutionDirectory()); 28 | // 29 | // string artifactsDir = Path.GetFullPath("artifacts"); 30 | // string logsDir = Path.Combine(artifactsDir, "logs"); 31 | // string buildLogFile = Path.Combine(logsDir, "build.binlog"); 32 | // string packagesDir = Path.Combine(artifactsDir, "packages"); 33 | // 34 | // string solutionFile = "Extensions.Hosting.AsyncInitialization.sln"; 35 | // string libraryProject = "src/Extensions.Hosting.AsyncInitialization/Extensions.Hosting.AsyncInitialization.csproj"; 36 | // string testProject = "tests/Extensions.Hosting.AsyncInitialization.Tests/Extensions.Hosting.AsyncInitialization.Tests.csproj"; 37 | // 38 | // Target( 39 | // "artifactDirectories", 40 | // () => 41 | // { 42 | // Directory.CreateDirectory(artifactsDir); 43 | // Directory.CreateDirectory(logsDir); 44 | // Directory.CreateDirectory(packagesDir); 45 | // }); 46 | // 47 | // Target( 48 | // "build", 49 | // DependsOn("artifactDirectories"), 50 | // () => Run( 51 | // "dotnet", 52 | // $"build -c \"{Configuration}\" /bl:\"{buildLogFile}\" \"{solutionFile}\"")); 53 | // 54 | // Target( 55 | // "test", 56 | // DependsOn("build"), 57 | // () => Run( 58 | // "dotnet", 59 | // $"test -c \"{Configuration}\" --no-build \"{testProject}\"")); 60 | // 61 | // Target( 62 | // "pack", 63 | // DependsOn("artifactDirectories", "build"), 64 | // () => Run( 65 | // "dotnet", 66 | // $"pack -c \"{Configuration}\" --no-build -o \"{packagesDir}\" \"{libraryProject}\"")); 67 | // 68 | // Target("default", DependsOn("test", "pack")); 69 | // 70 | // if (ShowHelp) 71 | // { 72 | // app.ShowHelp(); 73 | // app.Out.WriteLine("Bullseye help:"); 74 | // app.Out.WriteLine(); 75 | // await RunTargetsAndExitAsync(new[] { "-h" }); 76 | // return; 77 | // } 78 | // 79 | // await RunTargetsAndExitAsync(RemainingArguments); 80 | // } 81 | // 82 | // private static string GetSolutionDirectory() => 83 | // Path.GetFullPath(Path.Combine(GetScriptDirectory(), @"..\..")); 84 | // 85 | // private static string GetScriptDirectory([CallerFilePath] string filename = null) => Path.GetDirectoryName(filename); 86 | // } 87 | // } 88 | -------------------------------------------------------------------------------- /tools/build/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using static Bullseye.Targets; 3 | using static SimpleExec.Command; 4 | 5 | Directory.SetCurrentDirectory(GetSolutionDirectory()); 6 | 7 | string artifactsDir = Path.GetFullPath("artifacts"); 8 | string logsDir = Path.Combine(artifactsDir, "logs"); 9 | string buildLogFile = Path.Combine(logsDir, "build.binlog"); 10 | string packagesDir = Path.Combine(artifactsDir, "packages"); 11 | 12 | string solutionFile = "Extensions.Hosting.AsyncInitialization.sln"; 13 | 14 | Target( 15 | "artifactDirectories", 16 | () => 17 | { 18 | Directory.CreateDirectory(artifactsDir); 19 | Directory.CreateDirectory(logsDir); 20 | Directory.CreateDirectory(packagesDir); 21 | }); 22 | 23 | Target( 24 | "build", 25 | DependsOn("artifactDirectories"), 26 | () => Run( 27 | "dotnet", 28 | $"build -c Release /bl:\"{buildLogFile}\" \"{solutionFile}\"")); 29 | 30 | Target( 31 | "test", 32 | DependsOn("build"), 33 | action: () => Run( 34 | "dotnet", 35 | $"test -c Release --no-build")); 36 | 37 | Target( 38 | "pack", 39 | DependsOn("build", "test"), 40 | action: () => Run( 41 | "dotnet", 42 | $"pack -c Release --no-build -o \"{packagesDir}\"")); 43 | 44 | Target("default", DependsOn("pack")); 45 | 46 | await RunTargetsAndExitAsync(args); 47 | 48 | static string GetSolutionDirectory() => 49 | Path.GetFullPath(Path.Combine(GetScriptDirectory(), @"../..")); 50 | 51 | static string GetScriptDirectory([CallerFilePath] string filename = null) => Path.GetDirectoryName(filename); 52 | -------------------------------------------------------------------------------- /tools/build/build.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | true 7 | build 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | --------------------------------------------------------------------------------