├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── Rabbit.Extensions.sln ├── build ├── common.props └── version.props ├── samples └── ConsoleApp │ ├── ConsoleApp.csproj │ ├── Program.cs │ ├── UseCommandLineArgs.bat │ ├── UseEnvironmentVariables.bat │ └── appsettings.json ├── src ├── Configuration │ ├── README.md │ ├── Rabbit.Extensions.Configuration.Consul │ │ ├── ConsulConfigurationExtensions.cs │ │ ├── ConsulConfigurationProvider.cs │ │ ├── ConsulConfigurationSource.cs │ │ └── Rabbit.Extensions.Configuration.Consul.csproj │ └── Rabbit.Extensions.Configuration │ │ ├── Internal │ │ ├── TemplateEntry.cs │ │ └── TemplateRender.cs │ │ ├── Rabbit.Extensions.Configuration.csproj │ │ ├── TemplateRenderOptions.cs │ │ ├── TemplateSupportExtensions.cs │ │ ├── TemplateSupportOptions.cs │ │ └── Utilities │ │ └── TemplateUtil.cs ├── Rabbit.Extensions.Boot │ ├── Microsoft.Extensions.Configuration │ │ ├── ChainedBuilderExtensions.cs │ │ ├── ChainedConfigurationProvider.cs │ │ └── ChainedConfigurationSource.cs │ ├── Microsoft.Extensions.Hosting.Abstractions │ │ ├── BackgroundService.cs │ │ ├── EnvironmentName.cs │ │ ├── HostBuilderContext.cs │ │ ├── HostDefaults.cs │ │ ├── HostingAbstractionsHostBuilderExtensions.cs │ │ ├── HostingAbstractionsHostExtensions.cs │ │ ├── HostingEnvironmentExtensions.cs │ │ ├── IApplicationLifetime.cs │ │ ├── IHost.cs │ │ ├── IHostBuilder.cs │ │ ├── IHostLifetime.cs │ │ ├── IHostedService.cs │ │ ├── IHostingEnvironment.cs │ │ └── baseline.netcore.json │ ├── Microsoft.Extensions.Hosting │ │ ├── ConsoleLifetimeOptions.cs │ │ ├── HostBuilder.cs │ │ ├── HostOptions.cs │ │ ├── HostingHostBuilderExtensions.cs │ │ └── Internal │ │ │ ├── ApplicationLifetime.cs │ │ │ ├── ConfigureContainerAdapter.cs │ │ │ ├── ConsoleLifetime.cs │ │ │ ├── Host.cs │ │ │ ├── HostingEnvironment.cs │ │ │ ├── HostingLoggerExtensions.cs │ │ │ ├── IConfigureContainerAdapter.cs │ │ │ ├── IServiceFactoryAdapter.cs │ │ │ ├── LoggerEventIds.cs │ │ │ ├── ProcessLifetime.cs │ │ │ └── ServiceFactoryAdapter.cs │ ├── Rabbit.Extensions.Boot.csproj │ └── RabbitStarter.cs └── Rabbit.Extensions.DependencyInjection │ ├── Builder │ ├── RabbitContainerBuilder.cs │ ├── RabbitContainerBuilderExtensions.cs │ ├── ServiceBuilder.cs │ └── ServiceBuilderExtensions.cs │ ├── IDependency.cs │ ├── IServiceRegister.cs │ ├── ISupportKeyedService.cs │ ├── Internal │ ├── RabbitServiceScopeFactory.cs │ └── TypeKeyedUtilities.cs │ ├── Rabbit.Extensions.DependencyInjection.csproj │ ├── RabbitServiceDescriptor.cs │ ├── RabbitServiceProvider.cs │ ├── ServiceCollectionContainerBuilderExtensions.cs │ ├── ServiceDependencyInjectionExtensions.cs │ ├── ServiceDescriptorAttribute.cs │ ├── ServiceProviderServiceExtensions.cs │ ├── ServiceTypeMetadata.cs │ └── ServiceTypeMetadataExtensions.cs └── test ├── Configuration └── Rabbit.Extensions.Configuration.Test │ ├── Rabbit.Extensions.Configuration.Test.csproj │ └── TemplateSupportTest.cs └── Rabbit.Extensions.DependencyInjection.Test ├── DependencyInjectionTest.cs └── Rabbit.Extensions.DependencyInjection.Test.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 to .NET Core 2 | ## Configuration 3 | 1.Template Support 4 | 2.Consul Provider 5 | __[understand more](https://github.com/RabbitTeam/Rabbit-Extensions/tree/master/src/Configuration)__ 6 | -------------------------------------------------------------------------------- /Rabbit.Extensions.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27130.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Rabbit.Extensions.Configuration", "src\Configuration\Rabbit.Extensions.Configuration\Rabbit.Extensions.Configuration.csproj", "{6934D8D2-6993-4E8C-A118-8EDAFC8C6709}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Rabbit.Extensions.Configuration.Consul", "src\Configuration\Rabbit.Extensions.Configuration.Consul\Rabbit.Extensions.Configuration.Consul.csproj", "{81DB7700-4A63-45CB-8FC3-AD444689138B}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D4FCD154-5BBF-4996-AD71-CE87C5698F7E}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{0FDEAFEB-7926-4A63-BC38-F6BC223CBADD}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9147F8C9-9957-42CB-B854-C2E1010E7DFE}" 15 | ProjectSection(SolutionItems) = preProject 16 | build\common.props = build\common.props 17 | build\version.props = build\version.props 18 | EndProjectSection 19 | EndProject 20 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Configuration", "Configuration", "{765A2DE5-FC74-43A4-9A6D-3FC7BA467C2F}" 21 | EndProject 22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Configuration", "Configuration", "{AAC81674-3B5C-4041-ABD0-2F37BCE69089}" 23 | EndProject 24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Rabbit.Extensions.Configuration.Test", "test\Configuration\Rabbit.Extensions.Configuration.Test\Rabbit.Extensions.Configuration.Test.csproj", "{A023902F-6BEF-4DB9-A389-2CA4FB209F12}" 25 | EndProject 26 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{76380790-B349-4C9F-868B-39F81582A114}" 27 | EndProject 28 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleApp", "samples\ConsoleApp\ConsoleApp.csproj", "{89D4DDA4-5A85-4EC8-9D11-BBE20C9523C0}" 29 | EndProject 30 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Rabbit.Extensions.DependencyInjection", "src\Rabbit.Extensions.DependencyInjection\Rabbit.Extensions.DependencyInjection.csproj", "{3E5858AD-00F8-4AB6-ADFA-7EB55BFEA695}" 31 | EndProject 32 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Rabbit.Extensions.DependencyInjection.Test", "test\Rabbit.Extensions.DependencyInjection.Test\Rabbit.Extensions.DependencyInjection.Test.csproj", "{9E225D0C-5B7E-4FEA-8A07-D3B4FDB1BD8D}" 33 | EndProject 34 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Rabbit.Extensions.Boot", "src\Rabbit.Extensions.Boot\Rabbit.Extensions.Boot.csproj", "{A02F6865-8AFA-4493-9DA8-63A257274601}" 35 | EndProject 36 | Global 37 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 38 | Debug|Any CPU = Debug|Any CPU 39 | Release|Any CPU = Release|Any CPU 40 | EndGlobalSection 41 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 42 | {6934D8D2-6993-4E8C-A118-8EDAFC8C6709}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {6934D8D2-6993-4E8C-A118-8EDAFC8C6709}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {6934D8D2-6993-4E8C-A118-8EDAFC8C6709}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {6934D8D2-6993-4E8C-A118-8EDAFC8C6709}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {81DB7700-4A63-45CB-8FC3-AD444689138B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {81DB7700-4A63-45CB-8FC3-AD444689138B}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {81DB7700-4A63-45CB-8FC3-AD444689138B}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {81DB7700-4A63-45CB-8FC3-AD444689138B}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {A023902F-6BEF-4DB9-A389-2CA4FB209F12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {A023902F-6BEF-4DB9-A389-2CA4FB209F12}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {A023902F-6BEF-4DB9-A389-2CA4FB209F12}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {A023902F-6BEF-4DB9-A389-2CA4FB209F12}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {89D4DDA4-5A85-4EC8-9D11-BBE20C9523C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {89D4DDA4-5A85-4EC8-9D11-BBE20C9523C0}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {89D4DDA4-5A85-4EC8-9D11-BBE20C9523C0}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {89D4DDA4-5A85-4EC8-9D11-BBE20C9523C0}.Release|Any CPU.Build.0 = Release|Any CPU 58 | {3E5858AD-00F8-4AB6-ADFA-7EB55BFEA695}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 59 | {3E5858AD-00F8-4AB6-ADFA-7EB55BFEA695}.Debug|Any CPU.Build.0 = Debug|Any CPU 60 | {3E5858AD-00F8-4AB6-ADFA-7EB55BFEA695}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {3E5858AD-00F8-4AB6-ADFA-7EB55BFEA695}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {9E225D0C-5B7E-4FEA-8A07-D3B4FDB1BD8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 63 | {9E225D0C-5B7E-4FEA-8A07-D3B4FDB1BD8D}.Debug|Any CPU.Build.0 = Debug|Any CPU 64 | {9E225D0C-5B7E-4FEA-8A07-D3B4FDB1BD8D}.Release|Any CPU.ActiveCfg = Release|Any CPU 65 | {9E225D0C-5B7E-4FEA-8A07-D3B4FDB1BD8D}.Release|Any CPU.Build.0 = Release|Any CPU 66 | {A02F6865-8AFA-4493-9DA8-63A257274601}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 67 | {A02F6865-8AFA-4493-9DA8-63A257274601}.Debug|Any CPU.Build.0 = Debug|Any CPU 68 | {A02F6865-8AFA-4493-9DA8-63A257274601}.Release|Any CPU.ActiveCfg = Release|Any CPU 69 | {A02F6865-8AFA-4493-9DA8-63A257274601}.Release|Any CPU.Build.0 = Release|Any CPU 70 | {3ADD4E05-2792-4392-A927-5F1C3D4011B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 71 | {3ADD4E05-2792-4392-A927-5F1C3D4011B2}.Debug|Any CPU.Build.0 = Debug|Any CPU 72 | {3ADD4E05-2792-4392-A927-5F1C3D4011B2}.Release|Any CPU.ActiveCfg = Release|Any CPU 73 | {3ADD4E05-2792-4392-A927-5F1C3D4011B2}.Release|Any CPU.Build.0 = Release|Any CPU 74 | EndGlobalSection 75 | GlobalSection(SolutionProperties) = preSolution 76 | HideSolutionNode = FALSE 77 | EndGlobalSection 78 | GlobalSection(NestedProjects) = preSolution 79 | {6934D8D2-6993-4E8C-A118-8EDAFC8C6709} = {765A2DE5-FC74-43A4-9A6D-3FC7BA467C2F} 80 | {81DB7700-4A63-45CB-8FC3-AD444689138B} = {765A2DE5-FC74-43A4-9A6D-3FC7BA467C2F} 81 | {765A2DE5-FC74-43A4-9A6D-3FC7BA467C2F} = {D4FCD154-5BBF-4996-AD71-CE87C5698F7E} 82 | {AAC81674-3B5C-4041-ABD0-2F37BCE69089} = {0FDEAFEB-7926-4A63-BC38-F6BC223CBADD} 83 | {A023902F-6BEF-4DB9-A389-2CA4FB209F12} = {AAC81674-3B5C-4041-ABD0-2F37BCE69089} 84 | {89D4DDA4-5A85-4EC8-9D11-BBE20C9523C0} = {76380790-B349-4C9F-868B-39F81582A114} 85 | {3E5858AD-00F8-4AB6-ADFA-7EB55BFEA695} = {D4FCD154-5BBF-4996-AD71-CE87C5698F7E} 86 | {9E225D0C-5B7E-4FEA-8A07-D3B4FDB1BD8D} = {0FDEAFEB-7926-4A63-BC38-F6BC223CBADD} 87 | {A02F6865-8AFA-4493-9DA8-63A257274601} = {D4FCD154-5BBF-4996-AD71-CE87C5698F7E} 88 | {3ADD4E05-2792-4392-A927-5F1C3D4011B2} = {D4FCD154-5BBF-4996-AD71-CE87C5698F7E} 89 | EndGlobalSection 90 | GlobalSection(ExtensibilityGlobals) = postSolution 91 | SolutionGuid = {7F196E64-EAAA-41FC-8420-C6112B2060AF} 92 | EndGlobalSection 93 | EndGlobal 94 | -------------------------------------------------------------------------------- /build/common.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | $([System.IO.Path]::GetDirectoryName('$(MSBuildProjectDirectory)')) 6 | $([System.IO.Path]::GetFileName('$(ProjectParentDirectory)')) 7 | 8 | 9 | 10 | $(NoWarn);CS1591 11 | 12 | 13 | 14 | Rabbit Extensions 15 | https://github.com/RabbitTeam/Rabbit-Extensions 16 | git 17 | An extension library for .NET Core. 18 | Copyright (c) 2017 RabbitTeam. All rights reserved. 19 | majian 20 | true 21 | 22 | http://www.rabbithub.com/icon.png 23 | https://github.com/RabbitTeam/Rabbit-Extensions 24 | http://www.apache.org/licenses/LICENSE-2.0 25 | 26 | -------------------------------------------------------------------------------- /build/version.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1.0.0 5 | preview5 6 | 7 | -------------------------------------------------------------------------------- /samples/ConsoleApp/ConsoleApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | PreserveNewest 21 | 22 | 23 | Never 24 | 25 | 26 | Never 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /samples/ConsoleApp/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Rabbit.Extensions.Configuration; 3 | using System; 4 | 5 | namespace ConsoleApp 6 | { 7 | internal class Program 8 | { 9 | private static void Main(string[] args) 10 | { 11 | var configuration = new ConfigurationBuilder() 12 | .AddJsonFile("appsettings.json") 13 | .AddEnvironmentVariables() 14 | .AddCommandLine(args) 15 | .Build() 16 | .EnableTemplateSupport(); 17 | 18 | foreach (var section in configuration.GetSection("ServiceUrls").GetChildren()) 19 | { 20 | Console.WriteLine(section.Value); 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /samples/ConsoleApp/UseCommandLineArgs.bat: -------------------------------------------------------------------------------- 1 | dotnet run --ServiceHost=localhost 2 | pause -------------------------------------------------------------------------------- /samples/ConsoleApp/UseEnvironmentVariables.bat: -------------------------------------------------------------------------------- 1 | SET ServiceHost=localhost 2 | SET ServicePort=8080 3 | dotnet run 4 | pause -------------------------------------------------------------------------------- /samples/ConsoleApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ServicePort": 80, 3 | "Global": { 4 | "PathBase": "/api" 5 | }, 6 | "ServiceUrls": { 7 | "UserServiceUrl": "http://${ServiceHost}:${ServicePort}${Global:PathBase}/User", 8 | "AccountServiceUrl": "http://${ServiceHost}:${ServicePort}${Global:PathBase}/Account" 9 | } 10 | } -------------------------------------------------------------------------------- /src/Configuration/README.md: -------------------------------------------------------------------------------- 1 | # 配置文件模板支持 2 | ## 之前,我是这样的 3 | ![image](http://images2017.cnblogs.com/blog/384997/201709/384997-20170921080044884-826579002.png) 4 | 5 | 因为公司ip和家里机器的ip不一致,所以经常需要切换配置文件。 6 | 7 | 但根据这份配置文件,我更改健康检查的主机和端口就意味着我得改三个地方,然而一般情况下这三个地方都是一致的,如果这时候我能定义一个变量“ServiceHost”,然后这三个地方使用这个变量就好了。 8 | ## 现在,我是这样的 9 | ![image](https://images2017.cnblogs.com/blog/384997/201709/384997-20170921080045696-1839914749.png) 10 | 11 | 如果有变更需要只需改动几个变量值就可以了,不需要在满屏的配置文件里面去查看、搜索替换了。 12 | ## 配置信息变更重新渲染 13 | 当配置文件变更,进行Reload时,模板会自动进行重新渲染,不用担心渲染之后配置监控不可用的问题。 14 | ## Samples 15 | 配置文件如下: 16 | ![image](https://images2017.cnblogs.com/blog/384997/201709/384997-20170921080046181-200268300.png) 17 | 代码如下: 18 | ![image](https://images2017.cnblogs.com/blog/384997/201709/384997-20170921080046618-730649115.png) 19 | 效果1(dotnet run): 20 | ![image](https://images2017.cnblogs.com/blog/384997/201709/384997-20170921080047009-2088195109.png) 21 | 效果2(dotnet run --ServiceHost=localhost): 22 | ![image](https://images2017.cnblogs.com/blog/384997/201709/384997-20170921080047446-1509499016.png) 23 | 效果3(dotnet run --ServiceHost=localhost --ServicePort=5000): 24 | ![image](https://images2017.cnblogs.com/blog/384997/201709/384997-20170921080048103-843199483.png) 25 | # 基于 Consul 的 Configuration Provider 26 | -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration.Consul/ConsulConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | using Consul; 2 | using Microsoft.Extensions.Configuration; 3 | using System; 4 | 5 | namespace Rabbit.Extensions.Configuration.Consul 6 | { 7 | public static class ConsulConfigurationExtensions 8 | { 9 | public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, string url, string path = "/", string datacenter = null) 10 | { 11 | return builder.AddConsul(new Uri(url), path, datacenter); 12 | } 13 | 14 | public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, Uri address, string path = "/", string datacenter = null) 15 | { 16 | return builder.AddConsul(c => 17 | { 18 | c.Address = address; 19 | c.Datacenter = datacenter; 20 | }, s => 21 | { 22 | s.Path = path; 23 | }); 24 | } 25 | 26 | public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, ConsulClient consulClient, string path = "/") 27 | { 28 | return builder.AddConsul(s => 29 | { 30 | s.ConsulClient = consulClient; 31 | }); 32 | } 33 | 34 | public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, Action clientConfigure, Action configureSource) 35 | { 36 | return builder.AddConsul(s => 37 | { 38 | s.ConsulClient = new ConsulClient(clientConfigure); 39 | configureSource?.Invoke(s); 40 | }); 41 | } 42 | 43 | public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, 44 | Action configureSource) => builder.Add(configureSource); 45 | } 46 | } -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration.Consul/ConsulConfigurationProvider.cs: -------------------------------------------------------------------------------- 1 | using Consul; 2 | using Microsoft.Extensions.Configuration; 3 | using System; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace Rabbit.Extensions.Configuration.Consul 10 | { 11 | public class ConsulConfigurationProvider : ConfigurationProvider 12 | { 13 | private readonly ConsulConfigurationSource _source; 14 | 15 | private ulong _lastIndex; 16 | private readonly ReaderWriterLockSlim _readerWriterLockSlim = new ReaderWriterLockSlim(); 17 | 18 | public ConsulConfigurationProvider(ConsulConfigurationSource source) 19 | { 20 | _source = source; 21 | } 22 | 23 | #region Overrides of ConfigurationProvider 24 | 25 | /// 26 | /// 27 | /// Loads (or reloads) the data for this provider. 28 | /// 29 | public override void Load() 30 | { 31 | Task.Run(async () => 32 | { 33 | _lastIndex = await Load(null); 34 | TryWatch(OnReload); 35 | }).GetAwaiter().GetResult(); 36 | } 37 | 38 | /// 39 | /// 40 | /// Attempts to find a value with the given key, returns true if one is found, false otherwise. 41 | /// 42 | /// The key to lookup. 43 | /// The value found at key if one is found. 44 | /// True if key has a value, false otherwise. 45 | public override bool TryGet(string key, out string value) 46 | { 47 | try 48 | { 49 | _readerWriterLockSlim.EnterReadLock(); 50 | return base.TryGet(key, out value); 51 | } 52 | finally 53 | { 54 | _readerWriterLockSlim.ExitReadLock(); 55 | } 56 | } 57 | 58 | #endregion Overrides of ConfigurationProvider 59 | 60 | #region Private Method 61 | 62 | private void TryWatch(Action callback) 63 | { 64 | if (!_source.ReloadOnChange) 65 | return; 66 | 67 | Task.Factory.StartNew(async () => 68 | { 69 | while (true) 70 | { 71 | var result = await Load(_lastIndex); 72 | 73 | //no modify return 74 | if (result == _lastIndex) 75 | continue; 76 | 77 | _lastIndex = result; 78 | callback(); 79 | } 80 | }, TaskCreationOptions.LongRunning); 81 | } 82 | 83 | private async Task Load(ulong? index) 84 | { 85 | var result = await _source.ConsulClient.KV.List(_source.Path, 86 | index == null ? null : new QueryOptions { WaitIndex = index.Value }); 87 | 88 | if (!_source.Optional && result.StatusCode == HttpStatusCode.NotFound) 89 | throw new ArgumentException($"node: '{_source.Path}' not found."); 90 | 91 | Set(result); 92 | 93 | return result.LastIndex; 94 | } 95 | 96 | private void Set(QueryResult result) 97 | { 98 | if (result?.Response == null) 99 | return; 100 | _readerWriterLockSlim.EnterWriteLock(); 101 | try 102 | { 103 | Data = result.Response.ToDictionary(i => _source.KeyConver(i.Key), i => _source.ValueConver(i.Value)); 104 | } 105 | finally 106 | { 107 | _readerWriterLockSlim.ExitWriteLock(); 108 | } 109 | } 110 | 111 | #endregion Private Method 112 | } 113 | } -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration.Consul/ConsulConfigurationSource.cs: -------------------------------------------------------------------------------- 1 | using Consul; 2 | using Microsoft.Extensions.Configuration; 3 | using System; 4 | using System.Text; 5 | 6 | namespace Rabbit.Extensions.Configuration.Consul 7 | { 8 | public class ConsulConfigurationSource : IConfigurationSource 9 | { 10 | public ConsulClient ConsulClient { get; set; } 11 | public string Path { get; set; } 12 | public Func KeyConver { get; set; } 13 | public Func ValueConver { get; set; } 14 | public bool Optional { get; set; } = true; 15 | public bool ReloadOnChange { get; set; } = true; 16 | 17 | #region Implementation of IConfigurationSource 18 | 19 | /// 20 | /// 21 | /// Builds the for this source. 22 | /// 23 | /// The . 24 | /// An 25 | public IConfigurationProvider Build(IConfigurationBuilder builder) 26 | { 27 | EnsureDefaults(); 28 | return new ConsulConfigurationProvider(this); 29 | } 30 | 31 | #endregion Implementation of IConfigurationSource 32 | 33 | public void EnsureDefaults() 34 | { 35 | if (KeyConver == null) 36 | KeyConver = key => key.Replace("/", ConfigurationPath.KeyDelimiter); 37 | if (ValueConver == null) 38 | ValueConver = bytes => bytes == null ? null : Encoding.UTF8.GetString(bytes); 39 | 40 | if (string.IsNullOrWhiteSpace(Path)) 41 | Path = "/"; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration.Consul/Rabbit.Extensions.Configuration.Consul.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | netstandard2.0 6 | configuration config rabbit.extensions Microsoft.Extensions.Configuration consul 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration/Internal/TemplateEntry.cs: -------------------------------------------------------------------------------- 1 | using Rabbit.Extensions.Configuration.Utilities; 2 | using System; 3 | using System.Text; 4 | 5 | namespace Rabbit.Extensions.Configuration.Internal 6 | { 7 | public class TemplateEntry 8 | { 9 | public TemplateEntry(string key, string template) 10 | { 11 | Key = key; 12 | Template = template; 13 | } 14 | 15 | public string Key { get; } 16 | private string _template; 17 | 18 | public string Template 19 | { 20 | get => _template; 21 | set 22 | { 23 | _template = value; 24 | Builder = new StringBuilder(_template); 25 | Variables = TemplateUtil.GetVariables(value); 26 | } 27 | } 28 | 29 | public StringBuilder Builder { get; private set; } 30 | private string _value; 31 | 32 | public string Value 33 | { 34 | get => _value; 35 | private set 36 | { 37 | _value = value; 38 | Rendered = true; 39 | } 40 | } 41 | 42 | public bool Rendered { get; private set; } 43 | public string[] Variables { get; set; } 44 | 45 | public void Render(string[] variables, TemplateRenderOptions options) 46 | { 47 | if (Rendered) 48 | return; 49 | 50 | var target = options.Target; 51 | var source = options.Source; 52 | 53 | if (target == null) 54 | throw new ArgumentNullException(nameof(options.Target)); 55 | if (source == null) 56 | throw new ArgumentNullException(nameof(options.Source)); 57 | 58 | void Replace(string key) 59 | { 60 | var replaceText = TemplateUtil.GetReplaceText(key); 61 | var value = source[key]; 62 | if (value == null) 63 | { 64 | switch (options.VariableMissingAction) 65 | { 66 | case VariableMissingAction.UseKey: 67 | value = replaceText; 68 | break; 69 | 70 | case VariableMissingAction.UseEmpty: 71 | value = null; 72 | break; 73 | 74 | case VariableMissingAction.ThrowException: 75 | throw new ArgumentException($"missing key '{key}'."); 76 | default: 77 | throw new ArgumentOutOfRangeException(); 78 | } 79 | } 80 | Builder.Replace(replaceText, value); 81 | } 82 | 83 | foreach (var variable in variables) 84 | { 85 | Replace(variable); 86 | } 87 | 88 | Value = TemplateUtil.Escaped(Builder.ToString()); 89 | target[Key] = Value; 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration/Internal/TemplateRender.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Rabbit.Extensions.Configuration.Utilities; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | namespace Rabbit.Extensions.Configuration.Internal 8 | { 9 | public class TemplateRender 10 | { 11 | private readonly TemplateRenderOptions _options; 12 | private readonly IList _renders = new List(); 13 | 14 | public TemplateRender(TemplateRenderOptions options) 15 | { 16 | _options = options; 17 | AddEntries(options.Target.GetChildren()); 18 | } 19 | 20 | public void Render() 21 | { 22 | while (_renders.Any(i => !i.Rendered)) 23 | { 24 | foreach (var render in _renders) 25 | { 26 | CheckDependencies(render, new List()); 27 | 28 | var variables = FindVariables(render.Variables); 29 | if (variables == null || variables.All(i => i.Rendered)) 30 | { 31 | render.Render(render.Variables, _options); 32 | } 33 | } 34 | } 35 | } 36 | 37 | #region Private Method 38 | 39 | private void AddEntries(IEnumerable sections) 40 | { 41 | foreach (var section in sections) 42 | { 43 | var key = section.Path; 44 | var value = section.Value; 45 | 46 | if (value == null) 47 | { 48 | AddEntries(section.GetChildren()); 49 | } 50 | else if (TemplateUtil.NeedRender(value)) 51 | { 52 | AddEntry(key, value); 53 | } 54 | } 55 | } 56 | 57 | private void AddEntry(string key, string template) 58 | { 59 | var needRender = TemplateUtil.NeedRender(template); 60 | if (!needRender) 61 | return; 62 | 63 | var entry = new TemplateEntry(key, template); 64 | _renders.Add(entry); 65 | } 66 | 67 | private void CheckDependencies(TemplateEntry entry, ICollection dependencies) 68 | { 69 | var variables = entry.Variables; 70 | if (variables == null || !variables.Any()) 71 | return; 72 | 73 | foreach (var variable in variables) 74 | { 75 | var dependency = _renders.SingleOrDefault(i => i.Key == variable); 76 | if (dependency == null) 77 | continue; 78 | 79 | if (dependencies.Any(i => i.Key == dependency.Key)) 80 | throw new ArgumentException($"cyclic dependency '{entry.Key} > {string.Join(" > ", dependencies.Select(i => i.Key))}'.", entry.Key); 81 | 82 | dependencies.Add(dependency); 83 | 84 | if (dependency.Variables != null && dependency.Variables.Any()) 85 | { 86 | CheckDependencies(dependency, dependencies); 87 | } 88 | } 89 | } 90 | 91 | private TemplateEntry[] FindVariables(string[] variables) 92 | { 93 | return variables == null ? null : _renders.Where(i => variables.Contains(i.Key)).ToArray(); 94 | } 95 | 96 | #endregion Private Method 97 | } 98 | } -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration/Rabbit.Extensions.Configuration.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | netstandard2.0 6 | configuration config rabbit.extensions Microsoft.Extensions.Configuration configurationtemplate configtemplate 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration/TemplateRenderOptions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | 3 | namespace Rabbit.Extensions.Configuration 4 | { 5 | /// 6 | /// Can not find the replacement behavior of the variable. 7 | /// 8 | public enum VariableMissingAction 9 | { 10 | /// 11 | /// not replace. 12 | /// 13 | UseKey, 14 | 15 | /// 16 | /// replace empty. 17 | /// 18 | UseEmpty, 19 | 20 | /// 21 | /// throw exception. 22 | /// 23 | ThrowException 24 | } 25 | 26 | public class TemplateRenderOptions 27 | { 28 | /// 29 | /// Can not find the replacement behavior of the variable. 30 | /// 31 | public VariableMissingAction VariableMissingAction { get; set; } = VariableMissingAction.UseKey; 32 | 33 | /// 34 | /// handle target. 35 | /// 36 | public IConfiguration Target { get; set; } 37 | 38 | /// 39 | /// variable value source. 40 | /// 41 | public IConfiguration Source { get; set; } 42 | } 43 | } -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration/TemplateSupportExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Rabbit.Extensions.Configuration.Internal; 3 | using System; 4 | 5 | namespace Rabbit.Extensions.Configuration 6 | { 7 | public static class TemplateSupportExtensions 8 | { 9 | /// 10 | /// enable configuration template support. 11 | /// 12 | /// need enable configuration. 13 | /// options configure. 14 | /// configuration. 15 | public static T EnableTemplateSupport(this T target, Action configure = null) 16 | where T : IConfiguration 17 | { 18 | var options = new TemplateSupportOptions 19 | { 20 | Target = target, 21 | Source = target 22 | }; 23 | 24 | configure?.Invoke(options); 25 | 26 | EnableTemplateSupport(options); 27 | 28 | return target; 29 | } 30 | 31 | #region Private Method 32 | 33 | /// 34 | /// enable configuration template support. 35 | /// 36 | private static void EnableTemplateSupport(TemplateSupportOptions options) 37 | { 38 | if (options.Source == null) 39 | throw new ArgumentNullException(nameof(options.Source)); 40 | if (options.Source == null) 41 | throw new ArgumentNullException(nameof(options.Target)); 42 | 43 | var target = options.Target; 44 | 45 | //register rerender listen 46 | if (options.RerenderOnChange) 47 | target.GetReloadToken().RegisterChangeCallback(s => 48 | { 49 | EnableTemplateSupport(options); 50 | }, null); 51 | 52 | var render = new TemplateRender(options); 53 | render.Render(); 54 | } 55 | 56 | #endregion Private Method 57 | } 58 | } -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration/TemplateSupportOptions.cs: -------------------------------------------------------------------------------- 1 | namespace Rabbit.Extensions.Configuration 2 | { 3 | public class TemplateSupportOptions : TemplateRenderOptions 4 | { 5 | /// 6 | /// render the child configuration. 7 | /// 8 | public bool EnableChildren { get; set; } = true; 9 | 10 | /// 11 | /// configure source changes to render again. 12 | /// 13 | public bool RerenderOnChange { get; set; } = true; 14 | } 15 | } -------------------------------------------------------------------------------- /src/Configuration/Rabbit.Extensions.Configuration/Utilities/TemplateUtil.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text.RegularExpressions; 3 | 4 | namespace Rabbit.Extensions.Configuration.Utilities 5 | { 6 | public static class TemplateUtil 7 | { 8 | public static bool NeedRender(string template) 9 | { 10 | return !string.IsNullOrEmpty(template) && template.Contains("${"); 11 | } 12 | 13 | public static string[] GetVariables(string template) 14 | { 15 | var matches = Regex.Matches(template, @"[\\]?\${([^}]+)}"); 16 | var list = new List(); 17 | foreach (Match match in matches) 18 | { 19 | if (match.Groups[0].Value.StartsWith("\\")) 20 | continue; 21 | list.Add(match.Groups[1].Value); 22 | } 23 | return list.ToArray(); 24 | } 25 | 26 | public static string Escaped(string template) 27 | { 28 | return template.Replace("\\", ""); 29 | } 30 | 31 | public static string GetReplaceText(string key) 32 | { 33 | return $"${{{key}}}"; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Configuration/ChainedBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Microsoft.Extensions.Configuration 6 | { 7 | /// 8 | /// IConfigurationBuilder extension methods for the chaind configuration provider. 9 | /// 10 | public static class ChainedBuilderExtensions 11 | { 12 | /// 13 | /// Adds an existing configuration to . 14 | /// 15 | /// The to add to. 16 | /// The to add. 17 | /// The . 18 | public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder configurationBuilder, IConfiguration config) 19 | { 20 | if (configurationBuilder == null) 21 | { 22 | throw new ArgumentNullException(nameof(configurationBuilder)); 23 | } 24 | if (config == null) 25 | { 26 | throw new ArgumentNullException(nameof(config)); 27 | } 28 | 29 | configurationBuilder.Add(new ChainedConfigurationSource { Configuration = config }); 30 | return configurationBuilder; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Configuration/ChainedConfigurationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.Extensions.Primitives; 5 | 6 | namespace Microsoft.Extensions.Configuration 7 | { 8 | /// 9 | /// Chained implementation of 10 | /// 11 | public class ChainedConfigurationProvider : IConfigurationProvider 12 | { 13 | private readonly IConfiguration _config; 14 | 15 | /// 16 | /// Initialize a new instance from the source configuration. 17 | /// 18 | /// The source configuration. 19 | public ChainedConfigurationProvider(ChainedConfigurationSource source) 20 | { 21 | if (source == null) 22 | { 23 | throw new ArgumentNullException(nameof(source)); 24 | } 25 | if (source.Configuration == null) 26 | { 27 | throw new ArgumentNullException(nameof(source.Configuration)); 28 | } 29 | 30 | _config = source.Configuration; 31 | } 32 | 33 | /// 34 | /// Tries to get a configuration value for the specified key. 35 | /// 36 | /// The key. 37 | /// The value. 38 | /// True if a value for the specified key was found, otherwise false. 39 | public bool TryGet(string key, out string value) 40 | { 41 | value = _config[key]; 42 | return !string.IsNullOrEmpty(value); 43 | } 44 | 45 | /// 46 | /// Sets a configuration value for the specified key. 47 | /// 48 | /// The key. 49 | /// The value. 50 | public void Set(string key, string value) => _config[key] = value; 51 | 52 | /// 53 | /// Returns a change token if this provider supports change tracking, null otherwise. 54 | /// 55 | /// 56 | public IChangeToken GetReloadToken() => _config.GetReloadToken(); 57 | 58 | /// 59 | /// Loads configuration values from the source represented by this . 60 | /// 61 | public void Load() { } 62 | 63 | /// 64 | /// Returns the immediate descendant configuration keys for a given parent path based on this 65 | /// 's data and the set of keys returned by all the preceding 66 | /// s. 67 | /// 68 | /// The child keys returned by the preceding providers for the same parent path. 69 | /// The parent path. 70 | /// The child keys. 71 | public IEnumerable GetChildKeys( 72 | IEnumerable earlierKeys, 73 | string parentPath) 74 | { 75 | var section = parentPath == null ? _config : _config.GetSection(parentPath); 76 | var children = section.GetChildren(); 77 | var keys = new List(); 78 | keys.AddRange(children.Select(c => c.Key)); 79 | return keys.Concat(earlierKeys) 80 | .OrderBy(k => k, ConfigurationKeyComparer.Instance); 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Configuration/ChainedConfigurationSource.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | namespace Microsoft.Extensions.Configuration 5 | { 6 | /// 7 | /// Represents a chained IConfiguration as an . 8 | /// 9 | public class ChainedConfigurationSource : IConfigurationSource 10 | { 11 | /// 12 | /// The chained configuration. 13 | /// 14 | public IConfiguration Configuration { get; set; } 15 | 16 | /// 17 | /// Builds the for this source. 18 | /// 19 | /// The . 20 | /// A 21 | public IConfigurationProvider Build(IConfigurationBuilder builder) 22 | => new ChainedConfigurationProvider(this); 23 | } 24 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/BackgroundService.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.Extensions.Hosting 9 | { 10 | /// 11 | /// Base class for implementing a long running . 12 | /// 13 | public abstract class BackgroundService : IHostedService, IDisposable 14 | { 15 | private Task _executingTask; 16 | private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource(); 17 | 18 | /// 19 | /// This method is called when the starts. The implementation should return a task that represents 20 | /// the lifetime of the long running operation(s) being performed. 21 | /// 22 | /// Triggered when is called. 23 | /// A that represents the long running operations. 24 | protected abstract Task ExecuteAsync(CancellationToken stoppingToken); 25 | 26 | /// 27 | /// Triggered when the application host is ready to start the service. 28 | /// 29 | /// Indicates that the start process has been aborted. 30 | public virtual Task StartAsync(CancellationToken cancellationToken) 31 | { 32 | // Store the task we're executing 33 | _executingTask = ExecuteAsync(_stoppingCts.Token); 34 | 35 | // If the task is completed then return it, this will bubble cancellation and failure to the caller 36 | if (_executingTask.IsCompleted) 37 | { 38 | return _executingTask; 39 | } 40 | 41 | // Otherwise it's running 42 | return Task.CompletedTask; 43 | } 44 | 45 | /// 46 | /// Triggered when the application host is performing a graceful shutdown. 47 | /// 48 | /// Indicates that the shutdown process should no longer be graceful. 49 | public virtual async Task StopAsync(CancellationToken cancellationToken) 50 | { 51 | // Stop called without start 52 | if (_executingTask == null) 53 | { 54 | return; 55 | } 56 | 57 | try 58 | { 59 | // Signal cancellation to the executing method 60 | _stoppingCts.Cancel(); 61 | } 62 | finally 63 | { 64 | // Wait until the task completes or the stop token triggers 65 | await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken)); 66 | } 67 | 68 | } 69 | 70 | public virtual void Dispose() 71 | { 72 | _stoppingCts.Cancel(); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/EnvironmentName.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Hosting 5 | { 6 | /// 7 | /// Commonly used environment names. 8 | /// 9 | public static class EnvironmentName 10 | { 11 | public static readonly string Development = "Development"; 12 | public static readonly string Staging = "Staging"; 13 | public static readonly string Production = "Production"; 14 | } 15 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/HostBuilderContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using Microsoft.Extensions.Configuration; 6 | 7 | namespace Microsoft.Extensions.Hosting 8 | { 9 | /// 10 | /// Context containing the common services on the . Some properties may be null until set by the . 11 | /// 12 | public class HostBuilderContext 13 | { 14 | public HostBuilderContext(IDictionary properties) 15 | { 16 | Properties = properties ?? throw new System.ArgumentNullException(nameof(properties)); 17 | } 18 | 19 | /// 20 | /// The initialized by the . 21 | /// 22 | public IHostingEnvironment HostingEnvironment { get; set; } 23 | 24 | /// 25 | /// The containing the merged configuration of the application and the . 26 | /// 27 | public IConfiguration Configuration { get; set; } 28 | 29 | /// 30 | /// A central location for sharing state between components during the host building process. 31 | /// 32 | public IDictionary Properties { get; } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/HostDefaults.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Hosting 5 | { 6 | /// 7 | /// Constants for HostBuilder configuration keys. 8 | /// 9 | public static class HostDefaults 10 | { 11 | /// 12 | /// The configuration key used to set . 13 | /// 14 | public static readonly string ApplicationKey = "applicationName"; 15 | 16 | /// 17 | /// The configuration key used to set . 18 | /// 19 | public static readonly string EnvironmentKey = "environment"; 20 | 21 | /// 22 | /// The configuration key used to set 23 | /// and . 24 | /// 25 | public static readonly string ContentRootKey = "contentRoot"; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/HostingAbstractionsHostBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading; 5 | 6 | namespace Microsoft.Extensions.Hosting 7 | { 8 | public static class HostingAbstractionsHostBuilderExtensions 9 | { 10 | /// 11 | /// Start the host and listen on the specified urls. 12 | /// 13 | /// The to start. 14 | /// The . 15 | public static IHost Start(this IHostBuilder hostBuilder) 16 | { 17 | var host = hostBuilder.Build(); 18 | host.StartAsync(CancellationToken.None).GetAwaiter().GetResult(); 19 | return host; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/HostingAbstractionsHostExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Microsoft.Extensions.DependencyInjection; 8 | 9 | namespace Microsoft.Extensions.Hosting 10 | { 11 | public static class HostingAbstractionsHostExtensions 12 | { 13 | /// 14 | /// Starts the host synchronously. 15 | /// 16 | /// 17 | public static void Start(this IHost host) 18 | { 19 | host.StartAsync().GetAwaiter().GetResult(); 20 | } 21 | 22 | /// 23 | /// Attempts to gracefully stop the host with the given timeout. 24 | /// 25 | /// 26 | /// The timeout for stopping gracefully. Once expired the 27 | /// server may terminate any remaining active connections. 28 | /// 29 | public static Task StopAsync(this IHost host, TimeSpan timeout) 30 | { 31 | return host.StopAsync(new CancellationTokenSource(timeout).Token); 32 | } 33 | 34 | /// 35 | /// Block the calling thread until shutdown is triggered via Ctrl+C or SIGTERM. 36 | /// 37 | /// The running . 38 | public static void WaitForShutdown(this IHost host) 39 | { 40 | host.WaitForShutdownAsync().GetAwaiter().GetResult(); 41 | } 42 | 43 | /// 44 | /// Runs an application and block the calling thread until host shutdown. 45 | /// 46 | /// The to run. 47 | public static void Run(this IHost host) 48 | { 49 | host.RunAsync().GetAwaiter().GetResult(); 50 | } 51 | 52 | /// 53 | /// Runs an application and returns a Task that only completes when the token is triggered or shutdown is triggered. 54 | /// 55 | /// The to run. 56 | /// The token to trigger shutdown. 57 | public static async Task RunAsync(this IHost host, CancellationToken token = default) 58 | { 59 | using (host) 60 | { 61 | await host.StartAsync(token); 62 | 63 | await host.WaitForShutdownAsync(token); 64 | } 65 | } 66 | 67 | /// 68 | /// Returns a Task that completes when shutdown is triggered via the given token. 69 | /// 70 | /// The running . 71 | /// The token to trigger shutdown. 72 | public static async Task WaitForShutdownAsync(this IHost host, CancellationToken token = default) 73 | { 74 | var applicationLifetime = host.Services.GetService(); 75 | 76 | token.Register(state => 77 | { 78 | ((IApplicationLifetime)state).StopApplication(); 79 | }, 80 | applicationLifetime); 81 | 82 | var waitForStop = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); 83 | applicationLifetime.ApplicationStopping.Register(obj => 84 | { 85 | var tcs = (TaskCompletionSource)obj; 86 | tcs.TrySetResult(null); 87 | }, waitForStop); 88 | 89 | await waitForStop.Task; 90 | 91 | // Host will use its default ShutdownTimeout if none is specified. 92 | await host.StopAsync(); 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/HostingEnvironmentExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Hosting 7 | { 8 | /// 9 | /// Extension methods for . 10 | /// 11 | public static class HostingEnvironmentExtensions 12 | { 13 | /// 14 | /// Checks if the current hosting environment name is . 15 | /// 16 | /// An instance of . 17 | /// True if the environment name is , otherwise false. 18 | public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment) 19 | { 20 | if (hostingEnvironment == null) 21 | { 22 | throw new ArgumentNullException(nameof(hostingEnvironment)); 23 | } 24 | 25 | return hostingEnvironment.IsEnvironment(EnvironmentName.Development); 26 | } 27 | 28 | /// 29 | /// Checks if the current hosting environment name is . 30 | /// 31 | /// An instance of . 32 | /// True if the environment name is , otherwise false. 33 | public static bool IsStaging(this IHostingEnvironment hostingEnvironment) 34 | { 35 | if (hostingEnvironment == null) 36 | { 37 | throw new ArgumentNullException(nameof(hostingEnvironment)); 38 | } 39 | 40 | return hostingEnvironment.IsEnvironment(EnvironmentName.Staging); 41 | } 42 | 43 | /// 44 | /// Checks if the current hosting environment name is . 45 | /// 46 | /// An instance of . 47 | /// True if the environment name is , otherwise false. 48 | public static bool IsProduction(this IHostingEnvironment hostingEnvironment) 49 | { 50 | if (hostingEnvironment == null) 51 | { 52 | throw new ArgumentNullException(nameof(hostingEnvironment)); 53 | } 54 | 55 | return hostingEnvironment.IsEnvironment(EnvironmentName.Production); 56 | } 57 | 58 | /// 59 | /// Compares the current hosting environment name against the specified value. 60 | /// 61 | /// An instance of . 62 | /// Environment name to validate against. 63 | /// True if the specified name is the same as the current environment, otherwise false. 64 | public static bool IsEnvironment( 65 | this IHostingEnvironment hostingEnvironment, 66 | string environmentName) 67 | { 68 | if (hostingEnvironment == null) 69 | { 70 | throw new ArgumentNullException(nameof(hostingEnvironment)); 71 | } 72 | 73 | return string.Equals( 74 | hostingEnvironment.EnvironmentName, 75 | environmentName, 76 | StringComparison.OrdinalIgnoreCase); 77 | } 78 | } 79 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/IApplicationLifetime.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading; 5 | 6 | namespace Microsoft.Extensions.Hosting 7 | { 8 | /// 9 | /// Allows consumers to perform cleanup during a graceful shutdown. 10 | /// 11 | public interface IApplicationLifetime 12 | { 13 | /// 14 | /// Triggered when the application host has fully started and is about to wait 15 | /// for a graceful shutdown. 16 | /// 17 | CancellationToken ApplicationStarted { get; } 18 | 19 | /// 20 | /// Triggered when the application host is performing a graceful shutdown. 21 | /// Requests may still be in flight. Shutdown will block until this event completes. 22 | /// 23 | CancellationToken ApplicationStopping { get; } 24 | 25 | /// 26 | /// Triggered when the application host is performing a graceful shutdown. 27 | /// All requests should be complete at this point. Shutdown will block 28 | /// until this event completes. 29 | /// 30 | CancellationToken ApplicationStopped { get; } 31 | 32 | /// 33 | /// Requests termination of the current application. 34 | /// 35 | void StopApplication(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/IHost.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.Extensions.Hosting 9 | { 10 | /// 11 | /// A program abstraction. 12 | /// 13 | public interface IHost : IDisposable 14 | { 15 | /// 16 | /// The programs configured services. 17 | /// 18 | IServiceProvider Services { get; } 19 | 20 | /// 21 | /// Start the program. 22 | /// 23 | /// Used to abort program start. 24 | /// 25 | Task StartAsync(CancellationToken cancellationToken = default); 26 | 27 | /// 28 | /// Attempts to gracefully stop the program. 29 | /// 30 | /// Used to indicate when stop should no longer be graceful. 31 | /// 32 | Task StopAsync(CancellationToken cancellationToken = default); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/IHostBuilder.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.DependencyInjection; 8 | 9 | namespace Microsoft.Extensions.Hosting 10 | { 11 | /// 12 | /// A program initialization abstraction. 13 | /// 14 | public interface IHostBuilder 15 | { 16 | /// 17 | /// A central location for sharing state between components during the host building process. 18 | /// 19 | IDictionary Properties { get; } 20 | 21 | /// 22 | /// Set up the configuration for the builder itself. This will be used to initialize the 23 | /// for use later in the build process. This can be called multiple times and the results will be additive. 24 | /// 25 | /// The delegate for configuring the that will be used 26 | /// to construct the for the host. 27 | /// The same instance of the for chaining. 28 | IHostBuilder ConfigureHostConfiguration(Action configureDelegate); 29 | 30 | /// 31 | /// Sets up the configuration for the remainder of the build process and application. This can be called multiple times and 32 | /// the results will be additive. The results will be available at for 33 | /// subsequent operations, as well as in . 34 | /// 35 | /// The delegate for configuring the that will be used 36 | /// to construct the for the application. 37 | /// The same instance of the for chaining. 38 | IHostBuilder ConfigureAppConfiguration(Action configureDelegate); 39 | 40 | /// 41 | /// Adds services to the container. This can be called multiple times and the results will be additive. 42 | /// 43 | /// The delegate for configuring the that will be used 44 | /// to construct the . 45 | /// The same instance of the for chaining. 46 | IHostBuilder ConfigureServices(Action configureDelegate); 47 | 48 | /// 49 | /// Overrides the factory used to create the service provider. 50 | /// 51 | /// 52 | /// 53 | /// The same instance of the for chaining. 54 | IHostBuilder UseServiceProviderFactory(IServiceProviderFactory factory); 55 | 56 | /// 57 | /// Enables configuring the instantiated dependency container. This can be called multiple times and 58 | /// the results will be additive. 59 | /// 60 | /// 61 | /// 62 | /// The same instance of the for chaining. 63 | IHostBuilder ConfigureContainer(Action configureDelegate); 64 | 65 | /// 66 | /// Run the given actions to initialize the host. This can only be called once. 67 | /// 68 | /// An initialized 69 | IHost Build(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/IHostLifetime.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.Extensions.Hosting 9 | { 10 | public interface IHostLifetime 11 | { 12 | /// 13 | /// Called at the start of which will wait until the callback is invoked before 14 | /// continuing. This can be used to delay startup until signaled by an external event. 15 | /// 16 | /// A callback that will be invoked when the host should continue. 17 | /// State to pass to the callback. 18 | void RegisterDelayStartCallback(Action callback, object state); 19 | 20 | /// 21 | /// Called at the start of to register the given callback for initiating the 22 | /// application shutdown process. 23 | /// 24 | /// A callback to invoke when an external signal indicates the application should stop. 25 | /// State to pass to the callback. 26 | void RegisterStopCallback(Action callback, object state); 27 | 28 | /// 29 | /// Called from to indicate that the host as stopped and clean up resources. 30 | /// 31 | /// Used to indicate when stop should no longer be graceful. 32 | /// 33 | Task StopAsync(CancellationToken cancellationToken); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/IHostedService.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Microsoft.Extensions.Hosting 8 | { 9 | /// 10 | /// Defines methods for objects that are managed by the host. 11 | /// 12 | public interface IHostedService 13 | { 14 | /// 15 | /// Triggered when the application host is ready to start the service. 16 | /// 17 | /// Indicates that the start process has been aborted. 18 | Task StartAsync(CancellationToken cancellationToken); 19 | 20 | /// 21 | /// Triggered when the application host is performing a graceful shutdown. 22 | /// 23 | /// Indicates that the shutdown process should no longer be graceful. 24 | Task StopAsync(CancellationToken cancellationToken); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/IHostingEnvironment.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.FileProviders; 5 | 6 | namespace Microsoft.Extensions.Hosting 7 | { 8 | /// 9 | /// Provides information about the hosting environment an application is running in. 10 | /// 11 | public interface IHostingEnvironment 12 | { 13 | /// 14 | /// Gets or sets the name of the environment. The host automatically sets this property to the value of the 15 | /// of the "environment" key as specified in configuration. 16 | /// 17 | string EnvironmentName { get; set; } 18 | 19 | /// 20 | /// Gets or sets the name of the application. This property is automatically set by the host to the assembly containing 21 | /// the application entry point. 22 | /// 23 | string ApplicationName { get; set; } 24 | 25 | /// 26 | /// Gets or sets the absolute path to the directory that contains the application content files. 27 | /// 28 | string ContentRootPath { get; set; } 29 | 30 | /// 31 | /// Gets or sets an pointing at . 32 | /// 33 | IFileProvider ContentRootFileProvider { get; set; } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting.Abstractions/baseline.netcore.json: -------------------------------------------------------------------------------- 1 | { 2 | "AssemblyIdentity": "Microsoft.Extensions.Hosting.Abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", 3 | "Types": [ 4 | { 5 | "Name": "Microsoft.Extensions.Hosting.IHostedService", 6 | "Visibility": "Public", 7 | "Kind": "Interface", 8 | "Abstract": true, 9 | "ImplementedInterfaces": [], 10 | "Members": [ 11 | { 12 | "Kind": "Method", 13 | "Name": "StartAsync", 14 | "Parameters": [ 15 | { 16 | "Name": "cancellationToken", 17 | "Type": "System.Threading.CancellationToken" 18 | } 19 | ], 20 | "ReturnType": "System.Threading.Tasks.Task", 21 | "GenericParameter": [] 22 | }, 23 | { 24 | "Kind": "Method", 25 | "Name": "StopAsync", 26 | "Parameters": [ 27 | { 28 | "Name": "cancellationToken", 29 | "Type": "System.Threading.CancellationToken" 30 | } 31 | ], 32 | "ReturnType": "System.Threading.Tasks.Task", 33 | "GenericParameter": [] 34 | } 35 | ], 36 | "GenericParameters": [] 37 | } 38 | ] 39 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/ConsoleLifetimeOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Hosting 5 | { 6 | public class ConsoleLifetimeOptions 7 | { 8 | /// 9 | /// Indicates if host lifetime status messages should be supressed such as on startup. 10 | /// The default is false. 11 | /// 12 | public bool SuppressStatusMessages { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/HostBuilder.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.FileProviders; 10 | using Microsoft.Extensions.Hosting.Internal; 11 | 12 | namespace Microsoft.Extensions.Hosting 13 | { 14 | /// 15 | /// A program initialization utility. 16 | /// 17 | public class HostBuilder : IHostBuilder 18 | { 19 | private List> _configureHostConfigActions = new List>(); 20 | private List> _configureAppConfigActions = new List>(); 21 | private List> _configureServicesActions = new List>(); 22 | private List _configureContainerActions = new List(); 23 | private IServiceFactoryAdapter _serviceProviderFactory = new ServiceFactoryAdapter(new DefaultServiceProviderFactory()); 24 | private bool _hostBuilt; 25 | private IConfiguration _hostConfiguration; 26 | private IConfiguration _appConfiguration; 27 | private HostBuilderContext _hostBuilderContext; 28 | private IHostingEnvironment _hostingEnvironment; 29 | private IServiceProvider _appServices; 30 | 31 | /// 32 | /// A central location for sharing state between components during the host building process. 33 | /// 34 | public IDictionary Properties { get; } = new Dictionary(); 35 | 36 | /// 37 | /// Set up the configuration for the builder itself. This will be used to initialize the 38 | /// for use later in the build process. This can be called multiple times and the results will be additive. 39 | /// 40 | /// 41 | /// The same instance of the for chaining. 42 | public IHostBuilder ConfigureHostConfiguration(Action configureDelegate) 43 | { 44 | _configureHostConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); 45 | return this; 46 | } 47 | 48 | /// 49 | /// Sets up the configuration for the remainder of the build process and application. This can be called multiple times and 50 | /// the results will be additive. The results will be available at for 51 | /// subsequent operations, as well as in . 52 | /// 53 | /// 54 | /// The same instance of the for chaining. 55 | public IHostBuilder ConfigureAppConfiguration(Action configureDelegate) 56 | { 57 | _configureAppConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); 58 | return this; 59 | } 60 | 61 | /// 62 | /// Adds services to the container. This can be called multiple times and the results will be additive. 63 | /// 64 | /// 65 | /// The same instance of the for chaining. 66 | public IHostBuilder ConfigureServices(Action configureDelegate) 67 | { 68 | _configureServicesActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); 69 | return this; 70 | } 71 | 72 | /// 73 | /// Overrides the factory used to create the service provider. 74 | /// 75 | /// 76 | /// 77 | /// The same instance of the for chaining. 78 | public IHostBuilder UseServiceProviderFactory(IServiceProviderFactory factory) 79 | { 80 | _serviceProviderFactory = new ServiceFactoryAdapter(factory ?? throw new ArgumentNullException(nameof(factory))); 81 | return this; 82 | } 83 | 84 | /// 85 | /// Enables configuring the instantiated dependency container. This can be called multiple times and 86 | /// the results will be additive. 87 | /// 88 | /// 89 | /// 90 | /// The same instance of the for chaining. 91 | public IHostBuilder ConfigureContainer(Action configureDelegate) 92 | { 93 | _configureContainerActions.Add(new ConfigureContainerAdapter(configureDelegate 94 | ?? throw new ArgumentNullException(nameof(configureDelegate)))); 95 | return this; 96 | } 97 | 98 | /// 99 | /// Run the given actions to initialize the host. This can only be called once. 100 | /// 101 | /// An initialized 102 | public IHost Build() 103 | { 104 | if (_hostBuilt) 105 | { 106 | throw new InvalidOperationException("Build can only be called once."); 107 | } 108 | _hostBuilt = true; 109 | 110 | BuildHostConfiguration(); 111 | CreateHostingEnvironment(); 112 | CreateHostBuilderContext(); 113 | BuildAppConfiguration(); 114 | CreateServiceProvider(); 115 | 116 | return _appServices.GetRequiredService(); 117 | } 118 | 119 | private void BuildHostConfiguration() 120 | { 121 | var configBuilder = new ConfigurationBuilder(); 122 | foreach (var buildAction in _configureHostConfigActions) 123 | { 124 | buildAction(configBuilder); 125 | } 126 | _hostConfiguration = configBuilder.Build(); 127 | } 128 | 129 | private void CreateHostingEnvironment() 130 | { 131 | _hostingEnvironment = new HostingEnvironment() 132 | { 133 | ApplicationName = _hostConfiguration[HostDefaults.ApplicationKey], 134 | EnvironmentName = _hostConfiguration[HostDefaults.EnvironmentKey] ?? EnvironmentName.Production, 135 | ContentRootPath = ResolveContentRootPath(_hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory), 136 | }; 137 | _hostingEnvironment.ContentRootFileProvider = new PhysicalFileProvider(_hostingEnvironment.ContentRootPath); 138 | } 139 | 140 | private string ResolveContentRootPath(string contentRootPath, string basePath) 141 | { 142 | if (string.IsNullOrEmpty(contentRootPath)) 143 | { 144 | return basePath; 145 | } 146 | if (Path.IsPathRooted(contentRootPath)) 147 | { 148 | return contentRootPath; 149 | } 150 | return Path.Combine(Path.GetFullPath(basePath), contentRootPath); 151 | } 152 | 153 | private void CreateHostBuilderContext() 154 | { 155 | _hostBuilderContext = new HostBuilderContext(Properties) 156 | { 157 | HostingEnvironment = _hostingEnvironment, 158 | Configuration = _hostConfiguration 159 | }; 160 | } 161 | 162 | private void BuildAppConfiguration() 163 | { 164 | var configBuilder = new ConfigurationBuilder(); 165 | configBuilder.AddConfiguration(_hostConfiguration); 166 | foreach (var buildAction in _configureAppConfigActions) 167 | { 168 | buildAction(_hostBuilderContext, configBuilder); 169 | } 170 | _appConfiguration = configBuilder.Build(); 171 | _hostBuilderContext.Configuration = _appConfiguration; 172 | } 173 | 174 | private void CreateServiceProvider() 175 | { 176 | var services = new ServiceCollection(); 177 | services.AddSingleton(_hostingEnvironment); 178 | services.AddSingleton(_hostBuilderContext); 179 | services.AddSingleton(_appConfiguration); 180 | services.AddSingleton(); 181 | services.AddSingleton(); 182 | services.AddSingleton(); 183 | services.AddOptions(); 184 | services.AddLogging(); 185 | 186 | foreach (var configureServicesAction in _configureServicesActions) 187 | { 188 | configureServicesAction(_hostBuilderContext, services); 189 | } 190 | 191 | var containerBuilder = _serviceProviderFactory.CreateBuilder(services); 192 | 193 | foreach (var containerAction in _configureContainerActions) 194 | { 195 | containerAction.ConfigureContainer(_hostBuilderContext, containerBuilder); 196 | } 197 | 198 | _appServices = _serviceProviderFactory.CreateServiceProvider(containerBuilder); 199 | 200 | if (_appServices == null) 201 | { 202 | throw new InvalidOperationException($"The IServiceProviderFactory returned a null IServiceProvider."); 203 | } 204 | } 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/HostOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Hosting 7 | { 8 | /// 9 | /// Options for 10 | /// 11 | public class HostOptions 12 | { 13 | /// 14 | /// The default timeout for . 15 | /// 16 | public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5); 17 | } 18 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/HostingHostBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Hosting.Internal; 11 | using Microsoft.Extensions.Logging; 12 | 13 | namespace Microsoft.Extensions.Hosting 14 | { 15 | public static class HostingHostBuilderExtensions 16 | { 17 | /// 18 | /// Specify the environment to be used by the host. 19 | /// 20 | /// The to configure. 21 | /// The environment to host the application in. 22 | /// The . 23 | public static IHostBuilder UseEnvironment(this IHostBuilder hostBuilder, string environment) 24 | { 25 | return hostBuilder.ConfigureHostConfiguration(configBuilder => 26 | { 27 | configBuilder.AddInMemoryCollection(new[] 28 | { 29 | new KeyValuePair(HostDefaults.EnvironmentKey, 30 | environment ?? throw new ArgumentNullException(nameof(environment))) 31 | }); 32 | }); 33 | } 34 | 35 | /// 36 | /// Specify the content root directory to be used by the host. 37 | /// 38 | /// The to configure. 39 | /// Path to root directory of the application. 40 | /// The . 41 | public static IHostBuilder UseContentRoot(this IHostBuilder hostBuilder, string contentRoot) 42 | { 43 | return hostBuilder.ConfigureHostConfiguration(configBuilder => 44 | { 45 | configBuilder.AddInMemoryCollection(new[] 46 | { 47 | new KeyValuePair(HostDefaults.ContentRootKey, 48 | contentRoot ?? throw new ArgumentNullException(nameof(contentRoot))) 49 | }); 50 | }); 51 | } 52 | 53 | /// 54 | /// Adds a delegate for configuring the provided . This may be called multiple times. 55 | /// 56 | /// The to configure. 57 | /// The delegate that configures the . 58 | /// The same instance of the for chaining. 59 | public static IHostBuilder ConfigureLogging(this IHostBuilder hostBuilder, Action configureLogging) 60 | { 61 | return hostBuilder.ConfigureServices((context, collection) => collection.AddLogging(builder => configureLogging(context, builder))); 62 | } 63 | 64 | /// 65 | /// Adds a delegate for configuring the provided . This may be called multiple times. 66 | /// 67 | /// The to configure. 68 | /// The delegate that configures the . 69 | /// The same instance of the for chaining. 70 | public static IHostBuilder ConfigureLogging(this IHostBuilder hostBuilder, Action configureLogging) 71 | { 72 | return hostBuilder.ConfigureServices((context, collection) => collection.AddLogging(builder => configureLogging(builder))); 73 | } 74 | /// 75 | /// Sets up the configuration for the remainder of the build process and application. This can be called multiple times and 76 | /// the results will be additive. The results will be available at for 77 | /// subsequent operations, as well as in . 78 | /// 79 | /// The to configure. 80 | /// 81 | /// The same instance of the for chaining. 82 | public static IHostBuilder ConfigureAppConfiguration(this IHostBuilder hostBuilder, Action configureDelegate) 83 | { 84 | return hostBuilder.ConfigureAppConfiguration((context, builder) => configureDelegate(builder)); 85 | } 86 | 87 | /// 88 | /// Adds services to the container. This can be called multiple times and the results will be additive. 89 | /// 90 | /// The to configure. 91 | /// 92 | /// The same instance of the for chaining. 93 | public static IHostBuilder ConfigureServices(this IHostBuilder hostBuilder, Action configureDelegate) 94 | { 95 | return hostBuilder.ConfigureServices((context, collection) => configureDelegate(collection)); 96 | } 97 | 98 | /// 99 | /// Enables configuring the instantiated dependency container. This can be called multiple times and 100 | /// the results will be additive. 101 | /// 102 | /// 103 | /// The to configure. 104 | /// 105 | /// The same instance of the for chaining. 106 | public static IHostBuilder ConfigureContainer(this IHostBuilder hostBuilder, Action configureDelegate) 107 | { 108 | return hostBuilder.ConfigureContainer((context, builder) => configureDelegate(builder)); 109 | } 110 | 111 | /// 112 | /// Listens for Ctrl+C or SIGTERM and calls to start the shutdown process. 113 | /// This will unblock extensions like RunAsync and WaitForShutdownAsync. 114 | /// 115 | /// The to configure. 116 | /// The same instance of the for chaining. 117 | public static IHostBuilder UseConsoleLifetime(this IHostBuilder hostBuilder) 118 | { 119 | return hostBuilder.ConfigureServices((context, collection) => collection.AddSingleton()); 120 | } 121 | 122 | /// 123 | /// Enables console support, builds and starts the host, and waits for Ctrl+C or SIGTERM to shut down. 124 | /// 125 | /// The to configure. 126 | /// 127 | /// 128 | public static Task RunConsoleAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default) 129 | { 130 | return hostBuilder.UseConsoleLifetime().Build().RunAsync(cancellationToken); 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/ApplicationLifetime.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Threading; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace Microsoft.Extensions.Hosting.Internal 10 | { 11 | /// 12 | /// Allows consumers to perform cleanup during a graceful shutdown. 13 | /// 14 | public class ApplicationLifetime : IApplicationLifetime 15 | { 16 | private readonly CancellationTokenSource _startedSource = new CancellationTokenSource(); 17 | private readonly CancellationTokenSource _stoppingSource = new CancellationTokenSource(); 18 | private readonly CancellationTokenSource _stoppedSource = new CancellationTokenSource(); 19 | private readonly ILogger _logger; 20 | 21 | public ApplicationLifetime(ILogger logger) 22 | { 23 | _logger = logger; 24 | } 25 | 26 | /// 27 | /// Triggered when the application host has fully started and is about to wait 28 | /// for a graceful shutdown. 29 | /// 30 | public CancellationToken ApplicationStarted => _startedSource.Token; 31 | 32 | /// 33 | /// Triggered when the application host is performing a graceful shutdown. 34 | /// Request may still be in flight. Shutdown will block until this event completes. 35 | /// 36 | public CancellationToken ApplicationStopping => _stoppingSource.Token; 37 | 38 | /// 39 | /// Triggered when the application host is performing a graceful shutdown. 40 | /// All requests should be complete at this point. Shutdown will block 41 | /// until this event completes. 42 | /// 43 | public CancellationToken ApplicationStopped => _stoppedSource.Token; 44 | 45 | /// 46 | /// Signals the ApplicationStopping event and blocks until it completes. 47 | /// 48 | public void StopApplication() 49 | { 50 | // Lock on CTS to synchronize multiple calls to StopApplication. This guarantees that the first call 51 | // to StopApplication and its callbacks run to completion before subsequent calls to StopApplication, 52 | // which will no-op since the first call already requested cancellation, get a chance to execute. 53 | lock (_stoppingSource) 54 | { 55 | try 56 | { 57 | ExecuteHandlers(_stoppingSource); 58 | } 59 | catch (Exception ex) 60 | { 61 | _logger.ApplicationError(LoggerEventIds.ApplicationStoppingException, 62 | "An error occurred stopping the application", 63 | ex); 64 | } 65 | } 66 | } 67 | 68 | /// 69 | /// Signals the ApplicationStarted event and blocks until it completes. 70 | /// 71 | public void NotifyStarted() 72 | { 73 | try 74 | { 75 | ExecuteHandlers(_startedSource); 76 | } 77 | catch (Exception ex) 78 | { 79 | _logger.ApplicationError(LoggerEventIds.ApplicationStartupException, 80 | "An error occurred starting the application", 81 | ex); 82 | } 83 | } 84 | 85 | /// 86 | /// Signals the ApplicationStopped event and blocks until it completes. 87 | /// 88 | public void NotifyStopped() 89 | { 90 | try 91 | { 92 | ExecuteHandlers(_stoppedSource); 93 | } 94 | catch (Exception ex) 95 | { 96 | _logger.ApplicationError(LoggerEventIds.ApplicationStoppedException, 97 | "An error occurred stopping the application", 98 | ex); 99 | } 100 | } 101 | 102 | private void ExecuteHandlers(CancellationTokenSource cancel) 103 | { 104 | // Noop if this is already cancelled 105 | if (cancel.IsCancellationRequested) 106 | { 107 | return; 108 | } 109 | 110 | // Run the cancellation token callbacks 111 | cancel.Cancel(throwOnFirstException: false); 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/ConfigureContainerAdapter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Hosting.Internal 7 | { 8 | internal class ConfigureContainerAdapter : IConfigureContainerAdapter 9 | { 10 | private Action _action; 11 | 12 | public ConfigureContainerAdapter(Action action) 13 | { 14 | _action = action ?? throw new ArgumentNullException(nameof(action)); 15 | } 16 | 17 | public void ConfigureContainer(HostBuilderContext hostContext, object containerBuilder) 18 | { 19 | _action(hostContext, (TContainerBuilder)containerBuilder); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/ConsoleLifetime.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Microsoft.Extensions.Options; 8 | 9 | namespace Microsoft.Extensions.Hosting.Internal 10 | { 11 | /// 12 | /// Listens for Ctrl+C or SIGTERM and initiates shutdown. 13 | /// 14 | public class ConsoleLifetime : IHostLifetime 15 | { 16 | public ConsoleLifetime(IOptions options, IHostingEnvironment environment, IApplicationLifetime applicationLifetime) 17 | { 18 | Options = options?.Value ?? throw new ArgumentNullException(nameof(options)); 19 | Environment = environment ?? throw new ArgumentNullException(nameof(environment)); 20 | ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime)); 21 | } 22 | 23 | private ConsoleLifetimeOptions Options { get; } 24 | 25 | private IHostingEnvironment Environment { get; } 26 | 27 | private IApplicationLifetime ApplicationLifetime { get; } 28 | 29 | public void RegisterDelayStartCallback(Action callback, object state) 30 | { 31 | if (!Options.SuppressStatusMessages) 32 | { 33 | ApplicationLifetime.ApplicationStarted.Register(() => 34 | { 35 | Console.WriteLine("Application started. Press Ctrl+C to shut down."); 36 | Console.WriteLine($"Hosting environment: {Environment.EnvironmentName}"); 37 | Console.WriteLine($"Content root path: {Environment.ContentRootPath}"); 38 | }); 39 | } 40 | 41 | // Console applications start immediately. 42 | callback(state); 43 | } 44 | 45 | public void RegisterStopCallback(Action callback, object state) 46 | { 47 | AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => callback(state); 48 | Console.CancelKeyPress += (sender, e) => 49 | { 50 | e.Cancel = true; 51 | callback(state); 52 | }; 53 | } 54 | 55 | public Task StopAsync(CancellationToken cancellationToken) 56 | { 57 | // There's nothing to do here 58 | return Task.CompletedTask; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/Host.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Logging; 11 | using Microsoft.Extensions.Options; 12 | 13 | namespace Microsoft.Extensions.Hosting.Internal 14 | { 15 | internal class Host : IHost 16 | { 17 | private readonly ILogger _logger; 18 | private readonly IHostLifetime _hostLifetime; 19 | private readonly ApplicationLifetime _applicationLifetime; 20 | private readonly HostOptions _options; 21 | private IEnumerable _hostedServices; 22 | 23 | public Host(IServiceProvider services, IApplicationLifetime applicationLifetime, ILogger logger, 24 | IHostLifetime hostLifetime, IOptions options) 25 | { 26 | Services = services ?? throw new ArgumentNullException(nameof(services)); 27 | _applicationLifetime = (applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime))) as ApplicationLifetime; 28 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 29 | _hostLifetime = hostLifetime ?? throw new ArgumentNullException(nameof(hostLifetime)); 30 | _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); 31 | } 32 | 33 | public IServiceProvider Services { get; } 34 | 35 | public async Task StartAsync(CancellationToken cancellationToken = default) 36 | { 37 | _logger.Starting(); 38 | 39 | var delayStart = new TaskCompletionSource(); 40 | cancellationToken.Register(obj => ((TaskCompletionSource)obj).TrySetCanceled(), delayStart); 41 | _hostLifetime.RegisterDelayStartCallback(obj => ((TaskCompletionSource)obj).TrySetResult(null), delayStart); 42 | _hostLifetime.RegisterStopCallback(obj => (obj as IApplicationLifetime)?.StopApplication(), _applicationLifetime); 43 | 44 | await delayStart.Task; 45 | 46 | _hostedServices = Services.GetService>(); 47 | 48 | foreach (var hostedService in _hostedServices) 49 | { 50 | // Fire IHostedService.Start 51 | await hostedService.StartAsync(cancellationToken).ConfigureAwait(false); 52 | } 53 | 54 | // Fire IApplicationLifetime.Started 55 | _applicationLifetime?.NotifyStarted(); 56 | 57 | _logger.Started(); 58 | } 59 | 60 | public async Task StopAsync(CancellationToken cancellationToken = default) 61 | { 62 | _logger.Stopping(); 63 | 64 | using (var cts = new CancellationTokenSource(_options.ShutdownTimeout)) 65 | using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken)) 66 | { 67 | var token = linkedCts.Token; 68 | // Trigger IApplicationLifetime.ApplicationStopping 69 | _applicationLifetime?.StopApplication(); 70 | 71 | IList exceptions = new List(); 72 | if (_hostedServices != null) // Started? 73 | { 74 | foreach (var hostedService in _hostedServices.Reverse()) 75 | { 76 | token.ThrowIfCancellationRequested(); 77 | try 78 | { 79 | await hostedService.StopAsync(token).ConfigureAwait(false); 80 | } 81 | catch (Exception ex) 82 | { 83 | exceptions.Add(ex); 84 | } 85 | } 86 | } 87 | 88 | token.ThrowIfCancellationRequested(); 89 | await _hostLifetime.StopAsync(token); 90 | 91 | // Fire IApplicationLifetime.Stopped 92 | _applicationLifetime?.NotifyStopped(); 93 | 94 | if (exceptions.Count > 0) 95 | { 96 | var ex = new AggregateException("One or more hosted services failed to stop.", exceptions); 97 | _logger.StoppedWithException(ex); 98 | throw ex; 99 | } 100 | } 101 | 102 | _logger.Stopped(); 103 | } 104 | 105 | public void Dispose() 106 | { 107 | (Services as IDisposable)?.Dispose(); 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/HostingEnvironment.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.FileProviders; 5 | 6 | namespace Microsoft.Extensions.Hosting.Internal 7 | { 8 | public class HostingEnvironment : IHostingEnvironment 9 | { 10 | public string EnvironmentName { get; set; } 11 | 12 | public string ApplicationName { get; set; } 13 | 14 | public string ContentRootPath { get; set; } 15 | 16 | public IFileProvider ContentRootFileProvider { get; set; } 17 | } 18 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/HostingLoggerExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections; 6 | using System.Collections.Generic; 7 | using System.Globalization; 8 | using System.Reflection; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace Microsoft.Extensions.Hosting.Internal 12 | { 13 | internal static class HostingLoggerExtensions 14 | { 15 | public static void ApplicationError(this ILogger logger, EventId eventId, string message, Exception exception) 16 | { 17 | var reflectionTypeLoadException = exception as ReflectionTypeLoadException; 18 | if (reflectionTypeLoadException != null) 19 | { 20 | foreach (var ex in reflectionTypeLoadException.LoaderExceptions) 21 | { 22 | message = message + Environment.NewLine + ex.Message; 23 | } 24 | } 25 | 26 | logger.LogCritical( 27 | eventId: eventId, 28 | message: message, 29 | exception: exception); 30 | } 31 | 32 | public static void Starting(this ILogger logger) 33 | { 34 | if (logger.IsEnabled(LogLevel.Debug)) 35 | { 36 | logger.LogDebug( 37 | eventId: LoggerEventIds.Starting, 38 | message: "Hosting starting"); 39 | } 40 | } 41 | 42 | public static void Started(this ILogger logger) 43 | { 44 | if (logger.IsEnabled(LogLevel.Debug)) 45 | { 46 | logger.LogDebug( 47 | eventId: LoggerEventIds.Started, 48 | message: "Hosting started"); 49 | } 50 | } 51 | 52 | public static void Stopping(this ILogger logger) 53 | { 54 | if (logger.IsEnabled(LogLevel.Debug)) 55 | { 56 | logger.LogDebug( 57 | eventId: LoggerEventIds.Stopping, 58 | message: "Hosting stopping"); 59 | } 60 | } 61 | 62 | public static void Stopped(this ILogger logger) 63 | { 64 | if (logger.IsEnabled(LogLevel.Debug)) 65 | { 66 | logger.LogDebug( 67 | eventId: LoggerEventIds.Stopped, 68 | message: "Hosting stopped"); 69 | } 70 | } 71 | 72 | public static void StoppedWithException(this ILogger logger, Exception ex) 73 | { 74 | if (logger.IsEnabled(LogLevel.Debug)) 75 | { 76 | logger.LogDebug( 77 | eventId: LoggerEventIds.StoppedWithException, 78 | exception: ex, 79 | message: "Hosting shutdown exception"); 80 | } 81 | } 82 | } 83 | } 84 | 85 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/IConfigureContainerAdapter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Hosting.Internal 5 | { 6 | internal interface IConfigureContainerAdapter 7 | { 8 | void ConfigureContainer(HostBuilderContext hostContext, object containerBuilder); 9 | } 10 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/IServiceFactoryAdapter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.DependencyInjection; 6 | 7 | namespace Microsoft.Extensions.Hosting.Internal 8 | { 9 | internal interface IServiceFactoryAdapter 10 | { 11 | object CreateBuilder(IServiceCollection services); 12 | 13 | IServiceProvider CreateServiceProvider(object containerBuilder); 14 | } 15 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/LoggerEventIds.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Hosting.Internal 5 | { 6 | internal static class LoggerEventIds 7 | { 8 | public const int Starting = 1; 9 | public const int Started = 2; 10 | public const int Stopping = 3; 11 | public const int Stopped = 4; 12 | public const int StoppedWithException = 5; 13 | public const int ApplicationStartupException = 6; 14 | public const int ApplicationStoppingException = 7; 15 | public const int ApplicationStoppedException = 8; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/ProcessLifetime.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.Extensions.Hosting.Internal 9 | { 10 | public class ProcessLifetime : IHostLifetime 11 | { 12 | public void RegisterDelayStartCallback(Action callback, object state) 13 | { 14 | // Never delays start. 15 | callback(state); 16 | } 17 | 18 | public void RegisterStopCallback(Action callback, object state) 19 | { 20 | AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => callback(state); 21 | } 22 | 23 | public Task StopAsync(CancellationToken cancellationToken) 24 | { 25 | return Task.CompletedTask; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/Internal/ServiceFactoryAdapter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.DependencyInjection; 6 | 7 | namespace Microsoft.Extensions.Hosting.Internal 8 | { 9 | internal class ServiceFactoryAdapter : IServiceFactoryAdapter 10 | { 11 | private IServiceProviderFactory _serviceProviderFactory; 12 | 13 | public ServiceFactoryAdapter(IServiceProviderFactory serviceProviderFactory) 14 | { 15 | _serviceProviderFactory = serviceProviderFactory ?? throw new System.ArgumentNullException(nameof(serviceProviderFactory)); 16 | } 17 | 18 | public object CreateBuilder(IServiceCollection services) 19 | { 20 | return _serviceProviderFactory.CreateBuilder(services); 21 | } 22 | 23 | public IServiceProvider CreateServiceProvider(object containerBuilder) 24 | { 25 | return _serviceProviderFactory.CreateServiceProvider((TContainerBuilder)containerBuilder); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/Rabbit.Extensions.Boot.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | netstandard2.0 6 | Rabbit.Extensions.Boot 7 | Rabbit.Extensions.Boot 8 | latest 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.Boot/RabbitStarter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyModel; 2 | using Microsoft.Extensions.Hosting; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Reflection; 7 | using System.Threading.Tasks; 8 | 9 | namespace Rabbit.Extensions.Boot 10 | { 11 | public class RabbitBoot 12 | { 13 | public static async Task BuildHostBuilderAsync(Action configure = null, Func assemblyPredicate = null, Func typePredicate = null) 14 | { 15 | if (typePredicate == null) 16 | typePredicate = t => t.Name.EndsWith("Bootstrap"); 17 | 18 | var types = GetAssemblies(assemblyPredicate).SelectMany(i => i.ExportedTypes.Select(z => z.GetTypeInfo())).Where(typePredicate); 19 | 20 | IHostBuilder hostBuilder = new HostBuilder(); 21 | configure?.Invoke(hostBuilder); 22 | return await BuildHostBuilderAsync(hostBuilder, types); 23 | } 24 | 25 | public static async Task BuildHostBuilderAsync(IHostBuilder hostBuilder, IEnumerable starterTypes) 26 | { 27 | if (hostBuilder == null) 28 | throw new ArgumentNullException(nameof(hostBuilder)); 29 | if (starterTypes == null) 30 | throw new ArgumentNullException(nameof(starterTypes)); 31 | 32 | foreach (var startMethod in starterTypes.OrderByDescending(i => 33 | { 34 | var priorityProperty = i.GetProperty("Priority"); 35 | if (priorityProperty == null) 36 | return 20; 37 | return (int)priorityProperty.GetValue(null); 38 | }).SelectMany(GetStartMethods)) 39 | { 40 | var parameters = startMethod.GetParameters().Any() ? new object[] { hostBuilder } : null; 41 | var result = startMethod.Invoke(null, parameters); 42 | if (result is Task task) 43 | await task; 44 | } 45 | 46 | return hostBuilder; 47 | } 48 | 49 | private static IEnumerable GetAssemblies(Func predicate = null) 50 | { 51 | var assemblyNames = DependencyContext.Default.RuntimeLibraries.SelectMany(i => i.GetDefaultAssemblyNames(DependencyContext.Default)); 52 | if (predicate != null) 53 | assemblyNames = assemblyNames.Where(predicate).ToArray(); 54 | var assemblies = assemblyNames.Select(i => Assembly.Load(new AssemblyName(i.Name))).ToArray(); 55 | return assemblies; 56 | } 57 | 58 | private static IEnumerable GetStartMethods(TypeInfo starterType) 59 | { 60 | bool CheckParameters(MethodBase methodInfo) 61 | { 62 | var parameters = methodInfo.GetParameters(); 63 | switch (parameters.Length) 64 | { 65 | case 0: 66 | return true; 67 | 68 | case 1 when typeof(IHostBuilder).IsAssignableFrom(parameters[0].ParameterType): 69 | return true; 70 | 71 | default: 72 | return false; 73 | } 74 | } 75 | 76 | MethodInfo GetStartMethod(string name) 77 | { 78 | var methodInfo = starterType.GetMethod(name, BindingFlags.Static | BindingFlags.Public); 79 | if (methodInfo != null && CheckParameters(methodInfo)) 80 | return methodInfo; 81 | return null; 82 | } 83 | 84 | foreach (var methodInfo in new[] { "StartAsync", "Start" }.Select(GetStartMethod)) 85 | { 86 | if (methodInfo != null) 87 | yield return methodInfo; 88 | } 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/Builder/RabbitContainerBuilder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Rabbit.Extensions.DependencyInjection.Builder 6 | { 7 | public class RabbitContainerBuilder 8 | { 9 | private readonly ICollection _builders = new List(); 10 | 11 | public ServiceBuilder RegisterType(Type implementationType) 12 | { 13 | if (implementationType == null) 14 | throw new ArgumentNullException(nameof(implementationType)); 15 | 16 | var item = new ServiceBuilder 17 | { 18 | ImplementationType = implementationType 19 | }; 20 | _builders.Add(item); 21 | return item; 22 | } 23 | 24 | public ServiceBuilder RegisterInstance(object instance) 25 | { 26 | if (instance == null) 27 | throw new ArgumentNullException(nameof(instance)); 28 | 29 | var item = new ServiceBuilder 30 | { 31 | ImplementationInstance = instance 32 | }; 33 | _builders.Add(item); 34 | return item; 35 | } 36 | 37 | public ServiceBuilder Register(Func factory) 38 | { 39 | if (factory == null) 40 | throw new ArgumentNullException(nameof(factory)); 41 | 42 | var item = new ServiceBuilder 43 | { 44 | ImplementationFactory = factory 45 | }; 46 | _builders.Add(item); 47 | return item; 48 | } 49 | 50 | public void Build(IServiceCollection services) 51 | { 52 | foreach (var builder in _builders) 53 | { 54 | builder.Build(services); 55 | } 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/Builder/RabbitContainerBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace Rabbit.Extensions.DependencyInjection.Builder 2 | { 3 | public static class RabbitContainerBuilderExtensions 4 | { 5 | public static ServiceBuilder RegisterType(this RabbitContainerBuilder builder) 6 | { 7 | return builder.RegisterType(typeof(TImplementationType)); 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/Builder/ServiceBuilder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace Rabbit.Extensions.DependencyInjection.Builder 7 | { 8 | public class ServiceBuilder 9 | { 10 | public ServiceBuilder() 11 | { 12 | ServiceKeys = new List(); 13 | } 14 | 15 | internal Type ImplementationType { get; set; } 16 | internal ICollection ServiceKeys { get; set; } 17 | internal ServiceLifetime Lifetime { get; set; } 18 | internal object ImplementationInstance { get; set; } 19 | internal Func ImplementationFactory { get; set; } 20 | 21 | internal void Build(IServiceCollection services) 22 | { 23 | var descriptors = ServiceKeys.Distinct().Select(serviceKey => 24 | { 25 | var serviceType = serviceKey.ServiceType; 26 | ServiceDescriptor descriptor; 27 | if (serviceKey is KeyedServiceKey) 28 | { 29 | if (ImplementationFactory != null) 30 | descriptor = RabbitServiceDescriptor.Create(serviceType, ImplementationFactory, Lifetime); 31 | else if (ImplementationType != null) 32 | descriptor = RabbitServiceDescriptor.Create(serviceType, ImplementationType, Lifetime); 33 | else 34 | descriptor = RabbitServiceDescriptor.Create(serviceType, ImplementationInstance); 35 | 36 | ((RabbitServiceDescriptor)descriptor).ServiceKey = serviceKey; 37 | } 38 | else 39 | { 40 | if (ImplementationFactory != null) 41 | descriptor = new ServiceDescriptor(serviceType, ImplementationFactory, Lifetime); 42 | else if (ImplementationType != null) 43 | descriptor = new ServiceDescriptor(serviceType, ImplementationType, Lifetime); 44 | else 45 | descriptor = new ServiceDescriptor(serviceType, ImplementationInstance); 46 | } 47 | 48 | return descriptor; 49 | }).ToArray(); 50 | 51 | foreach (var descriptor in descriptors) 52 | { 53 | services.Add(descriptor); 54 | } 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/Builder/ServiceBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | 4 | namespace Rabbit.Extensions.DependencyInjection.Builder 5 | { 6 | public static class ServiceBuilderExtensions 7 | { 8 | public static ServiceBuilder As(this ServiceBuilder builder) 9 | { 10 | return builder.As(typeof(TService)); 11 | } 12 | 13 | public static ServiceBuilder As(this ServiceBuilder builder, Type serviceType) 14 | { 15 | builder.ServiceKeys.Add(new ServiceKey(serviceType)); 16 | return builder; 17 | } 18 | 19 | public static ServiceBuilder Singleton(this ServiceBuilder builder) 20 | { 21 | return builder.Lifetime(ServiceLifetime.Singleton); 22 | } 23 | 24 | public static ServiceBuilder Scoped(this ServiceBuilder builder) 25 | { 26 | return builder.Lifetime(ServiceLifetime.Scoped); 27 | } 28 | 29 | public static ServiceBuilder Transient(this ServiceBuilder builder) 30 | { 31 | return builder.Lifetime(ServiceLifetime.Transient); 32 | } 33 | 34 | public static ServiceBuilder Lifetime(this ServiceBuilder builder, ServiceLifetime lifetime) 35 | { 36 | builder.Lifetime = lifetime; 37 | return builder; 38 | } 39 | 40 | public static ServiceBuilder Named(this ServiceBuilder builder, string named) 41 | { 42 | return builder.Named(typeof(TService), named); 43 | } 44 | 45 | public static ServiceBuilder Named(this ServiceBuilder builder, Type serviceType, string named) 46 | { 47 | return builder.Keyed(serviceType, named); 48 | } 49 | 50 | public static ServiceBuilder Keyed(this ServiceBuilder builder, object keyed) 51 | { 52 | return builder.Keyed(typeof(TService), keyed); 53 | } 54 | 55 | public static ServiceBuilder Keyed(this ServiceBuilder builder, Type serviceType, object keyed) 56 | { 57 | builder.ServiceKeys.Add(new KeyedServiceKey(serviceType, keyed)); 58 | return builder; 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/IDependency.cs: -------------------------------------------------------------------------------- 1 | namespace Rabbit.Extensions.DependencyInjection 2 | { 3 | /// 4 | /// 表示实现者是一个基础依赖(当前容器区单例)。 5 | /// 6 | public interface IDependency 7 | { 8 | } 9 | 10 | /// 11 | /// 12 | /// 表示实现者是一个单列依赖。 13 | /// 14 | public interface ISingletonDependency : IDependency 15 | { 16 | } 17 | 18 | /// 19 | /// 20 | /// 表示实现者是一个瞬态依赖。 21 | /// 22 | public interface ITransientDependency : IDependency 23 | { 24 | } 25 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/IServiceRegister.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace Rabbit.Extensions.DependencyInjection 4 | { 5 | public interface IServiceRegister 6 | { 7 | void Register(IServiceCollection services); 8 | } 9 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/ISupportKeyedService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Rabbit.Extensions.DependencyInjection 4 | { 5 | public interface ISupportKeyedService 6 | { 7 | object GetKeyedService(Type serviceType, object keyed); 8 | } 9 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/Internal/RabbitServiceScopeFactory.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Rabbit.Extensions.DependencyInjection.Internal 6 | { 7 | internal class RabbitServiceScope : IServiceScope 8 | { 9 | public RabbitServiceScope(IServiceProvider rabbitServiceProvider) 10 | { 11 | ServiceProvider = rabbitServiceProvider; 12 | } 13 | 14 | #region Implementation of IDisposable 15 | 16 | /// 17 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. 18 | public void Dispose() 19 | { 20 | if (ServiceProvider is IDisposable disposable) 21 | { 22 | disposable.Dispose(); 23 | } 24 | } 25 | 26 | #endregion Implementation of IDisposable 27 | 28 | #region Implementation of IServiceScope 29 | 30 | /// 31 | /// 32 | /// The used to resolve dependencies from the scope. 33 | /// 34 | public IServiceProvider ServiceProvider { get; } 35 | 36 | #endregion Implementation of IServiceScope 37 | } 38 | 39 | internal class RabbitServiceScopeFactory : IServiceScopeFactory 40 | { 41 | private readonly IServiceProvider _serviceProvider; 42 | private readonly IEnumerable _serviceDescriptors; 43 | 44 | public RabbitServiceScopeFactory(IServiceProvider serviceProvider, IEnumerable serviceDescriptors) 45 | { 46 | _serviceProvider = serviceProvider; 47 | _serviceDescriptors = serviceDescriptors; 48 | } 49 | 50 | #region Implementation of IServiceScopeFactory 51 | 52 | /// 53 | /// 54 | /// Create an which 55 | /// contains an used to resolve dependencies from a 56 | /// newly created scope. 57 | /// 58 | /// 59 | /// An controlling the 60 | /// lifetime of the scope. Once this is disposed, any scoped services that have been resolved 61 | /// from the 62 | /// will also be disposed. 63 | /// 64 | public IServiceScope CreateScope() 65 | { 66 | return new RabbitServiceScope(new RabbitServiceProvider(_serviceProvider, _serviceDescriptors)); 67 | } 68 | 69 | #endregion Implementation of IServiceScopeFactory 70 | } 71 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/Internal/TypeKeyedUtilities.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using Castle.DynamicProxy.Generators; 3 | using System; 4 | 5 | namespace Rabbit.Extensions.DependencyInjection.Internal 6 | { 7 | public static class TypeKeyedUtilities 8 | { 9 | private static readonly INamingScope NamingScope = new NamingScope(); 10 | private static readonly ProxyGenerationOptions ProxyGenerationOptions = new ProxyGenerationOptions(); 11 | 12 | public static Type GetTypeKey() 13 | { 14 | var moduleScope = new ModuleScope(false, false, NamingScope, ModuleScope.DEFAULT_ASSEMBLY_NAME, ModuleScope.DEFAULT_FILE_NAME, ModuleScope.DEFAULT_ASSEMBLY_NAME, ModuleScope.DEFAULT_FILE_NAME); 15 | var proxyBuilder = new DefaultProxyBuilder(moduleScope); 16 | return proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ISupportKeyedService), null, ProxyGenerationOptions); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/Rabbit.Extensions.DependencyInjection.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | netstandard2.0 6 | dependencyinjection rabbit.extensions Microsoft.Extensions.DependencyInjection 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/RabbitServiceDescriptor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Rabbit.Extensions.DependencyInjection.Internal; 3 | using System; 4 | 5 | namespace Rabbit.Extensions.DependencyInjection 6 | { 7 | public interface IServiceKey 8 | { 9 | Type ServiceType { get; } 10 | } 11 | 12 | public struct KeyedServiceKey : IServiceKey 13 | { 14 | public Type ServiceType { get; } 15 | public object Keyed { get; } 16 | 17 | public KeyedServiceKey(Type serviceType, object keyed) 18 | { 19 | ServiceType = serviceType; 20 | Keyed = keyed; 21 | } 22 | 23 | #region Overrides of ValueType 24 | 25 | /// Indicates whether this instance and a specified object are equal. 26 | /// The object to compare with the current instance. 27 | /// true if obj and this instance are the same type and represent the same value; otherwise, false. 28 | public override bool Equals(object obj) 29 | { 30 | if (obj is KeyedServiceKey serviceKey) 31 | return Equals(serviceKey); 32 | return base.Equals(obj); 33 | } 34 | 35 | public bool Equals(KeyedServiceKey other) 36 | { 37 | return ServiceType == other.ServiceType && Equals(Keyed, other.Keyed); 38 | } 39 | 40 | /// Returns the hash code for this instance. 41 | /// A 32-bit signed integer that is the hash code for this instance. 42 | public override int GetHashCode() 43 | { 44 | unchecked 45 | { 46 | return ((ServiceType != null ? ServiceType.GetHashCode() : 0) * 397) ^ (Keyed != null ? Keyed.GetHashCode() : 0); 47 | } 48 | } 49 | 50 | /// Returns the fully qualified type name of this instance. 51 | /// The fully qualified type name. 52 | public override string ToString() 53 | { 54 | return $"ServiceType:{ServiceType},Keyed:{Keyed}"; 55 | } 56 | 57 | #endregion Overrides of ValueType 58 | } 59 | 60 | public struct ServiceKey : IServiceKey 61 | { 62 | public ServiceKey(Type serviceType) 63 | { 64 | ServiceType = serviceType; 65 | } 66 | 67 | #region Implementation of IServiceKey 68 | 69 | public Type ServiceType { get; } 70 | 71 | #endregion Implementation of IServiceKey 72 | 73 | #region Overrides of ValueType 74 | 75 | /// Indicates whether this instance and a specified object are equal. 76 | /// The object to compare with the current instance. 77 | /// true if obj and this instance are the same type and represent the same value; otherwise, false. 78 | public override bool Equals(object obj) 79 | { 80 | if (obj is ServiceKey serviceKey) 81 | return Equals(serviceKey); 82 | return base.Equals(obj); 83 | } 84 | 85 | public bool Equals(ServiceKey other) 86 | { 87 | return ServiceType == other.ServiceType; 88 | } 89 | 90 | /// Returns the hash code for this instance. 91 | /// A 32-bit signed integer that is the hash code for this instance. 92 | public override int GetHashCode() 93 | { 94 | return ServiceType != null ? ServiceType.GetHashCode() : 0; 95 | } 96 | 97 | /// Returns the fully qualified type name of this instance. 98 | /// The fully qualified type name. 99 | public override string ToString() 100 | { 101 | return $"ServiceType:{ServiceType}"; 102 | } 103 | 104 | #endregion Overrides of ValueType 105 | } 106 | 107 | public class RabbitServiceDescriptor : ServiceDescriptor 108 | { 109 | /// 110 | /// 111 | /// Initializes a new instance of with the specified . 112 | /// 113 | /// The of the service. 114 | /// The implementing the service. 115 | /// The of the service. 116 | public RabbitServiceDescriptor(Type serviceType, Type implementationType, ServiceLifetime lifetime) : base(serviceType, implementationType, lifetime) 117 | { 118 | } 119 | 120 | /// 121 | /// 122 | /// Initializes a new instance of with the specified 123 | /// as a . 124 | /// 125 | /// The of the service. 126 | /// The instance implementing the service. 127 | public RabbitServiceDescriptor(Type serviceType, object instance) : base(serviceType, instance) 128 | { 129 | } 130 | 131 | /// 132 | /// 133 | /// Initializes a new instance of with the specified . 134 | /// 135 | /// The of the service. 136 | /// A factory used for creating service instances. 137 | /// The of the service. 138 | public RabbitServiceDescriptor(Type serviceType, Func factory, ServiceLifetime lifetime) : base(serviceType, factory, lifetime) 139 | { 140 | } 141 | 142 | public IServiceKey ServiceKey { get; set; } 143 | 144 | public static RabbitServiceDescriptor Create(Type serviceType, Type implementationType, ServiceLifetime lifetime) 145 | { 146 | return Guarantee(serviceType, new RabbitServiceDescriptor(TypeKeyedUtilities.GetTypeKey(), implementationType, lifetime)); 147 | } 148 | 149 | public static RabbitServiceDescriptor Create(Type serviceType, object instance) 150 | { 151 | return Guarantee(serviceType, new RabbitServiceDescriptor(TypeKeyedUtilities.GetTypeKey(), instance)); 152 | } 153 | 154 | public static RabbitServiceDescriptor Create(Type serviceType, Func factory, ServiceLifetime lifetime) 155 | { 156 | return Guarantee(serviceType, new RabbitServiceDescriptor(TypeKeyedUtilities.GetTypeKey(), factory, lifetime)); 157 | } 158 | 159 | private static RabbitServiceDescriptor Guarantee(Type realType, RabbitServiceDescriptor rabbitServiceDescriptor) 160 | { 161 | // rabbitServiceDescriptor.RealType = realType; 162 | return rabbitServiceDescriptor; 163 | } 164 | 165 | public static RabbitServiceDescriptor Create(ServiceDescriptor descriptor) 166 | { 167 | RabbitServiceDescriptor newDescriptor; 168 | 169 | if (descriptor.ImplementationFactory != null) 170 | newDescriptor = Create(descriptor.ServiceType, descriptor.ImplementationFactory, descriptor.Lifetime); 171 | else if (descriptor.ImplementationType != null) 172 | newDescriptor = Create(descriptor.ServiceType, descriptor.ImplementationType, descriptor.Lifetime); 173 | else 174 | newDescriptor = Create(descriptor.ServiceType, descriptor.ImplementationInstance); 175 | 176 | return newDescriptor; 177 | } 178 | } 179 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/RabbitServiceProvider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Rabbit.Extensions.DependencyInjection.Internal; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | namespace Rabbit.Extensions.DependencyInjection 8 | { 9 | public class RabbitServiceProvider : IServiceProvider, ISupportKeyedService 10 | { 11 | private readonly IServiceProvider _serviceProvider; 12 | private readonly IReadOnlyCollection _rabbitServiceDescriptors; 13 | private readonly Lazy _serviceScopeFactoryLazy; 14 | 15 | public RabbitServiceProvider(IServiceProvider serviceProvider, IEnumerable serviceDescriptors) 16 | { 17 | _serviceProvider = serviceProvider; 18 | _rabbitServiceDescriptors = serviceDescriptors.OfType().ToArray(); 19 | _serviceScopeFactoryLazy = new Lazy(() => new RabbitServiceScopeFactory(this, _rabbitServiceDescriptors)); 20 | } 21 | 22 | #region Implementation of IServiceProvider 23 | 24 | /// 25 | /// Gets the service object of the specified type. 26 | /// An object that specifies the type of service object to get. 27 | /// A service object of type serviceType. -or- null if there is no service object of type serviceType. 28 | public object GetService(Type serviceType) 29 | { 30 | var serviceKey = new ServiceKey(serviceType); 31 | return GetService(serviceKey); 32 | } 33 | 34 | #endregion Implementation of IServiceProvider 35 | 36 | #region Implementation of ISupportKeyedService 37 | 38 | public object GetKeyedService(Type serviceType, object keyed) 39 | { 40 | var serviceKey = new KeyedServiceKey(serviceType, keyed); 41 | return GetService(serviceKey); 42 | } 43 | 44 | #endregion Implementation of ISupportKeyedService 45 | 46 | private object GetService(IServiceKey serviceKey) 47 | { 48 | var identityType = GetIdentityType(serviceKey); 49 | 50 | if (identityType == typeof(IServiceScopeFactory)) 51 | return _serviceScopeFactoryLazy.Value; 52 | 53 | return identityType == null ? null : _serviceProvider.GetService(identityType); 54 | } 55 | 56 | #region Private Method 57 | 58 | private Type GetIdentityType(IServiceKey serviceKey) 59 | { 60 | if (serviceKey is KeyedServiceKey) 61 | { 62 | var descriptor = _rabbitServiceDescriptors.LastOrDefault(i => i.ServiceKey.Equals(serviceKey)); 63 | return descriptor?.ServiceType; 64 | } 65 | return serviceKey.ServiceType; 66 | } 67 | 68 | #endregion Private Method 69 | } 70 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/ServiceCollectionContainerBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace Rabbit.Extensions.DependencyInjection 4 | { 5 | public static class ServiceCollectionContainerBuilderExtensions 6 | { 7 | public static RabbitServiceProvider BuildRabbitServiceProvider(this IServiceCollection services) 8 | { 9 | return new RabbitServiceProvider(services.BuildServiceProvider(), services); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/ServiceDependencyInjectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.DependencyModel; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Reflection; 7 | 8 | namespace Rabbit.Extensions.DependencyInjection 9 | { 10 | public static class ServiceDependencyInjectionExtensions 11 | { 12 | public static IServiceCollection AddServiceRegister(this IServiceCollection services, Func predicate = null) 13 | { 14 | var assemblies = GetAssemblies(predicate); 15 | return services.AddServiceRegister(assemblies); 16 | } 17 | 18 | public static IServiceCollection AddServiceRegister(this IServiceCollection services, IEnumerable assemblies) 19 | { 20 | //获取程序集中所有实现IServiceRegister接口的类型 21 | var types = assemblies.SelectMany(i => i.GetExportedTypes()) 22 | .Where(i => 23 | { 24 | var info = i.GetTypeInfo(); 25 | return info.IsClass && !info.IsAbstract && typeof(IServiceRegister).IsAssignableFrom(i); 26 | }); 27 | 28 | foreach (var type in types) 29 | { 30 | var constructor = type.GetConstructor(new Type[0]); 31 | var instance = (IServiceRegister)constructor.Invoke(new object[0]); 32 | instance.Register(services); 33 | } 34 | 35 | return services; 36 | } 37 | 38 | public static IServiceCollection AddInterfaceDependency(this IServiceCollection services, Func predicate = null) 39 | { 40 | var assemblies = GetAssemblies(predicate); 41 | return services.AddInterfaceDependency(assemblies); 42 | } 43 | 44 | 45 | 46 | public static IServiceCollection AddInterfaceDependency(this IServiceCollection services, IEnumerable assemblies) 47 | { 48 | //获取程序集中所有实现IDependency接口的类型 49 | var types = assemblies.SelectMany(i => i.GetExportedTypes()) 50 | .Where(i => 51 | { 52 | var info = i.GetTypeInfo(); 53 | return info.IsClass && !info.IsAbstract && typeof(IDependency).IsAssignableFrom(i); 54 | }); 55 | 56 | return services.AddInterfaceDependency(types); 57 | } 58 | 59 | public static IServiceCollection AddInterfaceDependency(this IServiceCollection services, IEnumerable types) 60 | { 61 | foreach (var type in types) 62 | RegisterDependency(type, services); 63 | 64 | return services; 65 | } 66 | 67 | public static IServiceCollection AddServiceExtensions(this IServiceCollection services) 68 | { 69 | var method = typeof(ServiceDependencyInjectionExtensions).GetMethod(nameof(GetServiceExtensions), BindingFlags.NonPublic | BindingFlags.Static); 70 | 71 | foreach (var service in services.ToArray().GroupBy(i => i.ServiceType).Select(i => i.First()).Where(i => !i.ServiceType.ContainsGenericParameters)) 72 | { 73 | var extensionsDescriptors = (IEnumerable)method.MakeGenericMethod(service.ServiceType).Invoke(null, null); 74 | foreach (var serviceDescriptor in extensionsDescriptors) 75 | { 76 | services.Add(serviceDescriptor); 77 | } 78 | } 79 | 80 | return services; 81 | } 82 | 83 | #region Private Method 84 | 85 | private static IEnumerable GetServiceExtensions() 86 | { 87 | yield return ServiceDescriptor.Transient(typeof(Lazy), provider => new Lazy(provider.GetRequiredService)); 88 | yield return ServiceDescriptor.Transient(typeof(Lazy>), provider => new Lazy>(provider.GetRequiredService>)); 89 | yield return ServiceDescriptor.Singleton(typeof(Func), provider => new Func(provider.GetRequiredService)); 90 | yield return ServiceDescriptor.Singleton(typeof(Func>), provider => new Func>(provider.GetRequiredService>)); 91 | } 92 | 93 | private static IEnumerable GetAssemblies(Func predicate = null) 94 | { 95 | var assemblyNames = DependencyContext.Default.RuntimeLibraries.SelectMany(i => i.GetDefaultAssemblyNames(DependencyContext.Default)); 96 | if (predicate != null) 97 | assemblyNames = assemblyNames.Where(predicate).ToArray(); 98 | var assemblies = assemblyNames.Select(i => Assembly.Load(new AssemblyName(i.Name))).ToArray(); 99 | return assemblies; 100 | } 101 | 102 | private static void RegisterDependency(Type type, IServiceCollection services) 103 | { 104 | foreach (var serviceDescriptor in GetServiceDescriptors(type)) 105 | { 106 | if (serviceDescriptor != null) 107 | services.Add(serviceDescriptor); 108 | } 109 | } 110 | 111 | private static IEnumerable GetServiceDescriptors(Type implementationType) 112 | { 113 | var interfaces = implementationType 114 | .GetInterfaces() 115 | .Where(i => typeof(IDependency).IsAssignableFrom(i)) 116 | .ToArray(); 117 | 118 | //没有任何标识依赖的接口 119 | if (!interfaces.Any()) 120 | yield break; 121 | 122 | //处理类本身实现的接口 123 | var baseDependency = interfaces.FirstOrDefault(); 124 | var defaultDependencys = new[] { typeof(IDependency), typeof(ISingletonDependency), typeof(ITransientDependency) }; 125 | if (defaultDependencys.Contains(baseDependency)) 126 | yield return GetServiceDescriptor(implementationType, implementationType); 127 | 128 | //处理其它服务类型 129 | foreach (var interfaceType in interfaces.Where(i => !defaultDependencys.Contains(i))) 130 | { 131 | yield return GetServiceDescriptor(interfaceType, implementationType); 132 | } 133 | } 134 | 135 | private static ServiceDescriptor GetServiceDescriptor(Type serviceType, Type implementationType) 136 | { 137 | ServiceDescriptor descriptor = null; 138 | if (typeof(ISingletonDependency).IsAssignableFrom(serviceType)) 139 | { 140 | descriptor = ServiceDescriptor.Singleton(serviceType, implementationType); 141 | } 142 | else if (typeof(ITransientDependency).IsAssignableFrom(serviceType)) 143 | { 144 | descriptor = ServiceDescriptor.Transient(serviceType, implementationType); 145 | } 146 | else if (typeof(IDependency).IsAssignableFrom(serviceType)) 147 | { 148 | descriptor = ServiceDescriptor.Scoped(serviceType, implementationType); 149 | } 150 | return descriptor; 151 | } 152 | 153 | #endregion Private Method 154 | 155 | 156 | 157 | #region add metadata dependency by only attribute 158 | 159 | public static IServiceCollection AddMetadataDependency(this IServiceCollection services, Func predicate = null) 160 | { 161 | var assemblies = GetAssemblies(predicate); 162 | 163 | var types = assemblies.SelectMany(i => i.GetExportedTypes()) 164 | .Where(t=>t.GetTypeInfo() 165 | .IsDefined(typeof(ServiceDescriptorAttribute),inherit: true) 166 | ); 167 | 168 | foreach (var type in types) 169 | { 170 | var typeInfo = type.GetTypeInfo(); 171 | 172 | var attributes = typeInfo.GetCustomAttributes().ToArray(); 173 | 174 | // Check if the type has multiple attributes with same ServiceType. 175 | var duplicates = attributes 176 | .GroupBy(s => s.ServiceType) 177 | .SelectMany(grp => grp.Skip(1)); 178 | 179 | if (duplicates.Any()) 180 | { 181 | throw new InvalidOperationException($@"Type ""{type.FullName}"" has multiple ServiceDescriptor attributes with the same service type."); 182 | } 183 | 184 | foreach (var attribute in attributes) 185 | { 186 | var serviceTypes = getRequireMetadataServiceTypes(type, attribute); 187 | 188 | foreach (var serviceType in serviceTypes) 189 | { 190 | // 191 | var descriptor = new ServiceDescriptor(serviceType, type, attribute.Lifetime); 192 | 193 | services.Add(descriptor); 194 | 195 | if (serviceType.IsInterface) 196 | { 197 | var extensionDescriptor = (ServiceDescriptor)getMetadataServiceDescriptorMethodInfo 198 | .MakeGenericMethod(descriptor.ServiceType) 199 | .Invoke(null, new object[] { descriptor.ImplementationType }); 200 | 201 | services.Add(extensionDescriptor); 202 | 203 | ServiceTypeMetadataExtensions.AddMetadata(descriptor.ImplementationType, attribute.Name); 204 | 205 | } 206 | 207 | } 208 | } 209 | } 210 | 211 | return services; 212 | } 213 | 214 | /// 215 | /// get support metadata required interface and class . 216 | /// such as a class:interface, required types as class and interface. 217 | /// 218 | /// 219 | /// 220 | /// 221 | private static IEnumerable getRequireMetadataServiceTypes(Type type, ServiceDescriptorAttribute attribute) 222 | { 223 | var typeInfo = type.GetTypeInfo(); 224 | 225 | var serviceType = attribute.ServiceType; 226 | 227 | if (serviceType == null) 228 | { 229 | yield return type; 230 | 231 | foreach (var implementedInterface in typeInfo.ImplementedInterfaces) 232 | { 233 | yield return implementedInterface; 234 | } 235 | 236 | if (typeInfo.BaseType != null && typeInfo.BaseType != typeof(object)) 237 | { 238 | yield return typeInfo.BaseType; 239 | } 240 | 241 | yield break; 242 | } 243 | 244 | var serviceTypeInfo = serviceType.GetTypeInfo(); 245 | 246 | if (!serviceTypeInfo.IsAssignableFrom(typeInfo)) 247 | { 248 | throw new InvalidOperationException($@"Type ""{typeInfo.FullName}"" is not assignable to ""${serviceTypeInfo.FullName}""."); 249 | } 250 | 251 | yield return serviceType; 252 | yield return type; 253 | 254 | } 255 | 256 | static MethodInfo getMetadataServiceDescriptorMethodInfo = typeof(ServiceDependencyInjectionExtensions).GetMethod(nameof(GetMetadataServiceDescriptor), BindingFlags.NonPublic | BindingFlags.Static); 257 | private static ServiceDescriptor GetMetadataServiceDescriptor(Type ImplementationType) 258 | { 259 | 260 | return ServiceDescriptor.Transient(typeof(Lazy), 261 | provider => 262 | new Lazy( 263 | () => 264 | (T)provider.GetRequiredService(ImplementationType), 265 | ServiceTypeMetadataExtensions.GetServiceTypeMetadata(ImplementationType) 266 | )); 267 | 268 | } 269 | 270 | #endregion 271 | 272 | 273 | } 274 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/ServiceDescriptorAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Microsoft.Extensions.DependencyInjection; 5 | 6 | namespace Rabbit.Extensions.DependencyInjection 7 | { 8 | 9 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] 10 | public class ServiceDescriptorAttribute : Attribute 11 | { 12 | public ServiceDescriptorAttribute() : this(null) { } 13 | 14 | public ServiceDescriptorAttribute(Type serviceType) : this(serviceType, ServiceLifetime.Transient) { } 15 | 16 | public ServiceDescriptorAttribute(Type serviceType, ServiceLifetime lifetime) 17 | { 18 | ServiceType = serviceType; 19 | Lifetime = lifetime; 20 | } 21 | 22 | public ServiceDescriptorAttribute(string name, Type serviceType, 23 | ServiceLifetime lifetime = ServiceLifetime.Transient) : this(serviceType, ServiceLifetime.Transient) 24 | { 25 | this.Name = name; 26 | } 27 | 28 | 29 | public Type ServiceType { get; } 30 | 31 | public string Name { set; get; } 32 | 33 | public ServiceLifetime Lifetime { get; } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/ServiceProviderServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | 5 | namespace Rabbit.Extensions.DependencyInjection 6 | { 7 | public static class ServiceProviderServiceExtensions 8 | { 9 | public static TService GetKeyedService(this IServiceProvider serviceProvider, object keyed) 10 | { 11 | return (TService)serviceProvider.GetKeyedService(typeof(TService), keyed); 12 | } 13 | 14 | public static object GetKeyedService(this IServiceProvider serviceProvider, Type serviceType, object keyed) 15 | { 16 | if (serviceProvider is ISupportKeyedService supportKeyedService) 17 | return supportKeyedService.GetKeyedService(serviceType, keyed); 18 | throw new NotSupportedException("not support keyedService."); 19 | } 20 | 21 | public static object GetRequiredKeyedService(this IServiceProvider serviceProvider, Type serviceType, object keyed) 22 | { 23 | var service = serviceProvider.GetKeyedService(serviceType, keyed); 24 | if (service == null) 25 | throw new InvalidOperationException("NoServiceRegistered."); 26 | return service; 27 | } 28 | 29 | public static TService GetRequiredKeyedService(this IServiceProvider serviceProvider, object keyed) 30 | { 31 | return (TService)serviceProvider.GetRequiredKeyedService(typeof(TService), keyed); 32 | } 33 | 34 | public static TService GetNamedService(this IServiceProvider serviceProvider, string named) 35 | { 36 | return (TService)serviceProvider.GetNamedService(typeof(TService), named); 37 | } 38 | 39 | public static object GetNamedService(this IServiceProvider serviceProvider, Type serviceType, string named) 40 | { 41 | return serviceProvider.GetKeyedService(serviceType, named); 42 | } 43 | 44 | public static object GetRequiredNamedService(this IServiceProvider serviceProvider, Type serviceType, string named) 45 | { 46 | var service = serviceProvider.GetNamedService(serviceType, named); 47 | if (service == null) 48 | throw new InvalidOperationException("NoServiceRegistered."); 49 | return service; 50 | } 51 | 52 | public static TService GetRequiredNamedService(this IServiceProvider serviceProvider, string named) 53 | { 54 | return (TService)serviceProvider.GetRequiredNamedService(typeof(TService), named); 55 | } 56 | 57 | #region 58 | 59 | public static TService GetServiceByMetadata(this IServiceProvider serviceProvider, 60 | Predicate predicate) 61 | { 62 | var serviceQuery = QueryServiceByMeatdata(serviceProvider); 63 | 64 | var service = serviceQuery.FirstOrDefault(s => predicate.Invoke(s.Metadata)); 65 | 66 | return service != null ? service.Value : default(TService); 67 | } 68 | 69 | public static IEnumerable GetServicesByMetadata(this IServiceProvider serviceProvider, 70 | Predicate predicate = null) 71 | { 72 | var serviceQuery = QueryServiceByMeatdata(serviceProvider); 73 | 74 | if (predicate != null) 75 | serviceQuery = serviceQuery.Where(s => predicate.Invoke(s.Metadata)); 76 | 77 | var services = serviceQuery.Select(s => s.Value); 78 | 79 | return services; 80 | } 81 | 82 | 83 | 84 | private static IEnumerable> QueryServiceByMeatdata(IServiceProvider serviceProvider) 85 | { 86 | var serviceQuery = (IEnumerable>) 87 | serviceProvider.GetService(typeof(IEnumerable>)); 88 | 89 | return serviceQuery; 90 | } 91 | 92 | #endregion 93 | 94 | 95 | 96 | 97 | } 98 | } -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/ServiceTypeMetadata.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Rabbit.Extensions.DependencyInjection 6 | { 7 | public class ServiceTypeMetadata 8 | { 9 | public string Name { set; get; } 10 | 11 | public string NameSpace { set; get; } 12 | 13 | public Type ServiceType { set; get; } 14 | 15 | public string Description { set; get; } 16 | 17 | public object Configuration { set; get; } 18 | 19 | public TConfig GetConfig() 20 | { 21 | return (TConfig)Configuration; 22 | } 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Rabbit.Extensions.DependencyInjection/ServiceTypeMetadataExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Rabbit.Extensions.DependencyInjection 7 | { 8 | internal class ServiceTypeMetadataExtensions 9 | { 10 | private static ConcurrentDictionary serviceTypesMetadataList = 11 | new ConcurrentDictionary(); 12 | 13 | 14 | 15 | public static void AddMetadata(Type serviceType, string name = null) 16 | { 17 | if (!serviceTypesMetadataList.ContainsKey(serviceType)) 18 | { 19 | var smd = GetDefaultServiceTypeMetadata(serviceType); 20 | 21 | if (!string.IsNullOrEmpty(name)) smd.Name = name; 22 | 23 | serviceTypesMetadataList.TryAdd(serviceType, smd); 24 | 25 | } 26 | } 27 | 28 | 29 | public static void AddMetadata(Type serviceType, ServiceTypeMetadata metadata) 30 | { 31 | if (!serviceTypesMetadataList.ContainsKey(serviceType)) 32 | { 33 | if (metadata != null) 34 | { 35 | serviceTypesMetadataList.TryAdd(serviceType, metadata); 36 | } 37 | else 38 | { 39 | serviceTypesMetadataList.TryAdd(serviceType, 40 | GetDefaultServiceTypeMetadata(serviceType)); 41 | } 42 | } 43 | 44 | 45 | } 46 | 47 | 48 | public static ServiceTypeMetadata GetDefaultServiceTypeMetadata(Type serviceType) 49 | { 50 | return new ServiceTypeMetadata() { Name = serviceType.Name, NameSpace = serviceType.Namespace, ServiceType = serviceType }; 51 | } 52 | 53 | public static ServiceTypeMetadata GetServiceTypeMetadata(Type serviceType) 54 | { 55 | ServiceTypeMetadata metadata = null; 56 | if (!serviceTypesMetadataList.TryGetValue(serviceType, out metadata)) 57 | { 58 | metadata = GetDefaultServiceTypeMetadata(serviceType); 59 | } 60 | 61 | return metadata; 62 | } 63 | 64 | 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /test/Configuration/Rabbit.Extensions.Configuration.Test/Rabbit.Extensions.Configuration.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /test/Configuration/Rabbit.Extensions.Configuration.Test/TemplateSupportTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using Xunit; 9 | 10 | namespace Rabbit.Extensions.Configuration.Test 11 | { 12 | public class TemplateSupportTest 13 | { 14 | [Theory(DisplayName = "BasicTest")] 15 | [InlineData("port", "80")] 16 | [InlineData("url", "http://localhost:80/User/Get/?p1=${notReplace}&t=${t}")] 17 | [InlineData("ch:url", "http://localhost:80/User/Get/?p1=${notReplace}&t=${t}_test")] 18 | [InlineData("ch:c:url", "http://localhost:80/User/Get/?p1=${notReplace}&t=${t}_test_test")] 19 | public void BasicTest(string key, string value) 20 | { 21 | var configuration = GetConfiguration(); 22 | 23 | Assert.Equal(value, configuration[key]); 24 | } 25 | 26 | [Fact(DisplayName = "ReloadOnChangeTest")] 27 | public void ReloadOnChangeTest() 28 | { 29 | var filePath = Path.Combine(AppContext.BaseDirectory, "temp.txt"); 30 | 31 | try 32 | { 33 | void SetName(string name) 34 | { 35 | File.WriteAllText(filePath, JsonConvert.SerializeObject(new 36 | { 37 | firstName = name, 38 | lastName = "johnson", 39 | fullName = "${firstName} ${lastName}" 40 | })); 41 | } 42 | 43 | SetName("ben"); 44 | 45 | var configuration = new ConfigurationBuilder() 46 | .AddJsonFile(filePath, false, true) 47 | .Build() 48 | .EnableTemplateSupport(); 49 | 50 | Assert.Equal("ben johnson", configuration["fullName"]); 51 | 52 | var autoResetEvent = new AutoResetEvent(false); 53 | configuration.GetReloadToken().RegisterChangeCallback(async s => 54 | { 55 | await Task.Delay(50); 56 | autoResetEvent.Set(); 57 | }, null); 58 | 59 | SetName("michael"); 60 | autoResetEvent.WaitOne(5000); 61 | 62 | //new value 63 | Assert.Equal("michael johnson", configuration["fullName"]); 64 | } 65 | finally 66 | { 67 | if (File.Exists(filePath)) 68 | File.Delete(filePath); 69 | } 70 | } 71 | 72 | [Fact(DisplayName = "CyclicDependencyTest")] 73 | public void CyclicDependencyTest() 74 | { 75 | var data = new Dictionary 76 | { 77 | {"key1", "${key3}"}, 78 | {"key2", "${key1}"}, 79 | {"key3", "${key2}"} 80 | }; 81 | var exception = Assert.Throws("key1", () => 82 | { 83 | GetConfiguration(data); 84 | }); 85 | Assert.Equal("cyclic dependency 'key1 > key3 > key2 > key1'.\r\nParameter name: key1", exception.Message); 86 | } 87 | 88 | [Theory(DisplayName = "VariableMissingTest")] 89 | [InlineData(VariableMissingAction.ThrowException, null)] 90 | [InlineData(VariableMissingAction.UseKey, "http://localhost:80/User/Get/?p1=${notReplace}&t=${t}")] 91 | [InlineData(VariableMissingAction.UseEmpty, "http://localhost:80/User/Get/?p1=${notReplace}&t=")] 92 | public void VariableMissingTest(VariableMissingAction variableMissingAction, string value) 93 | { 94 | IConfiguration Init() 95 | { 96 | return GetConfiguration(configure: c => { c.VariableMissingAction = variableMissingAction; }); 97 | } 98 | 99 | if (variableMissingAction == VariableMissingAction.ThrowException) 100 | { 101 | var exception = Assert.Throws((Func)Init); 102 | Assert.Equal("missing key 't'.", exception.Message); 103 | } 104 | else 105 | { 106 | var configuration = Init(); 107 | Assert.Equal(value, configuration["url"]); 108 | } 109 | } 110 | 111 | #region Private Method 112 | 113 | private static IConfigurationRoot GetConfiguration(IDictionary memoryConfiguration = null, Action configure = null) 114 | { 115 | if (memoryConfiguration == null) 116 | memoryConfiguration = GetMemoryConfiguration(); 117 | 118 | return new ConfigurationBuilder() 119 | .AddInMemoryCollection(memoryConfiguration) 120 | .Build() 121 | .EnableTemplateSupport(configure); 122 | } 123 | 124 | private static Dictionary GetMemoryConfiguration() 125 | { 126 | return new Dictionary 127 | { 128 | {"url", "http://${service:host}:${port}/${controller}/${action}/?p1=\\${notReplace}&t=${t}"}, 129 | {"service:host", "localhost"}, 130 | {"port", "80"}, 131 | {"controller", "User"}, 132 | {"action", "Get"}, 133 | {"ch:url","${url}_test" }, 134 | {"ch:c:url","${ch:url}_test" } 135 | }; 136 | } 137 | 138 | #endregion Private Method 139 | } 140 | } -------------------------------------------------------------------------------- /test/Rabbit.Extensions.DependencyInjection.Test/DependencyInjectionTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Collections.Generic; 4 | using Xunit; 5 | using System.Linq; 6 | 7 | namespace Rabbit.Extensions.DependencyInjection.Test 8 | { 9 | public class TestServiceRegister : IServiceRegister 10 | { 11 | #region Implementation of IServiceRegister 12 | 13 | public void Register(IServiceCollection services) 14 | { 15 | services.AddSingleton("test"); 16 | } 17 | 18 | #endregion Implementation of IServiceRegister 19 | } 20 | 21 | public interface ITestService1 : IDependency 22 | { 23 | } 24 | 25 | public interface ITestService2 : ITransientDependency 26 | { 27 | } 28 | 29 | public interface ITestService3 : ISingletonDependency 30 | { 31 | } 32 | 33 | public class TestService : ITestService1, ITestService2, ITestService3 34 | { 35 | } 36 | 37 | public interface ITestService { } 38 | 39 | 40 | 41 | [ServiceDescriptor("t1", typeof(ITestService), ServiceLifetime.Scoped)] 42 | public class TestService1 : ITestService { } 43 | 44 | [ServiceDescriptor("t2", typeof(ITestService), ServiceLifetime.Scoped)] 45 | public class TestService2 : ITestService { } 46 | 47 | 48 | 49 | 50 | 51 | public class DependencyInjectionTest 52 | { 53 | [Fact] 54 | public void ServiceRegisterTest() 55 | { 56 | var services = new ServiceCollection() 57 | .AddServiceRegister() 58 | .BuildServiceProvider(); 59 | 60 | Assert.Equal("test", services.GetRequiredService()); 61 | } 62 | 63 | [Fact] 64 | public void InterfaceDependencyTest() 65 | { 66 | var services = new ServiceCollection() 67 | .AddInterfaceDependency() 68 | .BuildServiceProvider(); 69 | 70 | Assert.Equal(services.GetRequiredService().GetHashCode(), services.GetRequiredService().GetHashCode()); 71 | Assert.NotEqual(services.GetRequiredService().GetHashCode(), services.GetRequiredService().GetHashCode()); 72 | Assert.Equal(services.GetRequiredService().GetHashCode(), services.GetRequiredService().GetHashCode()); 73 | 74 | using (var scope = services.GetRequiredService().CreateScope()) 75 | { 76 | Assert.NotEqual(scope.ServiceProvider.GetRequiredService().GetHashCode(), services.GetRequiredService().GetHashCode()); 77 | Assert.NotEqual(scope.ServiceProvider.GetRequiredService().GetHashCode(), services.GetRequiredService().GetHashCode()); 78 | Assert.Equal(scope.ServiceProvider.GetRequiredService().GetHashCode(), services.GetRequiredService().GetHashCode()); 79 | } 80 | } 81 | 82 | [Fact] 83 | public void LazyResolveTest() 84 | { 85 | var services = new ServiceCollection() 86 | .AddInterfaceDependency() 87 | .AddServiceExtensions() 88 | .BuildServiceProvider(); 89 | 90 | Assert.NotEqual(services.GetRequiredService>(), services.GetRequiredService>()); 91 | Assert.NotEqual(services.GetRequiredService>().Value, services.GetRequiredService>().Value); 92 | 93 | Assert.NotNull(services.GetRequiredService>>()); 94 | } 95 | 96 | [Fact] 97 | public void FuncResolveTest() 98 | { 99 | var services = new ServiceCollection() 100 | .AddInterfaceDependency() 101 | .AddServiceExtensions() 102 | .BuildServiceProvider(); 103 | 104 | Assert.Equal(services.GetRequiredService>()(), services.GetRequiredService>()()); 105 | Assert.Equal(services.GetRequiredService>(), services.GetRequiredService>()); 106 | Assert.NotEqual(services.GetRequiredService>()(), services.GetRequiredService>()()); 107 | } 108 | 109 | [Fact] 110 | public void AttributeAndMetadataTest() 111 | { 112 | var services = new ServiceCollection() 113 | .AddMetadataDependency() 114 | .BuildServiceProvider(); 115 | 116 | var ts = services.GetServiceByMetadata( 117 | metadata => metadata.Name == "t1" 118 | ); 119 | 120 | Assert.Equal(ts?.GetType(), typeof(TestService1)); 121 | 122 | var query = services.GetServicesByMetadata(); 123 | 124 | Assert.Equal(query.Count(), 2); 125 | 126 | 127 | } 128 | 129 | 130 | } 131 | } -------------------------------------------------------------------------------- /test/Rabbit.Extensions.DependencyInjection.Test/Rabbit.Extensions.DependencyInjection.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | --------------------------------------------------------------------------------