├── .editorconfig ├── .github └── workflows │ └── dotnet.yml ├── .gitignore ├── LICENSE ├── README.md ├── SourceInject.sln ├── src └── SourceInject │ ├── Generator.cs │ ├── Properties │ └── launchSettings.json │ ├── ServicesReceiver.cs │ └── SourceInject.csproj └── test ├── ConsoleApp ├── ConsoleApp.csproj ├── ExampleService.cs └── Program.cs ├── Lib ├── Lib.csproj └── ServiceOnLib.cs └── SourceInjectTests ├── GeneratorTests.cs └── SourceInjectTests.csproj /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 4 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | max_line_length = 100 10 | tab_width = 4 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | 15 | [*.json] 16 | indent_size = 2 17 | 18 | [*.yml] 19 | indent_size = 2 20 | 21 | [*.cs] 22 | #added by vs 23 | dotnet_style_operator_placement_when_wrapping = beginning_of_line 24 | end_of_line = crlf 25 | dotnet_style_coalesce_expression = true:suggestion 26 | dotnet_style_null_propagation = true:suggestion 27 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion 28 | dotnet_style_prefer_auto_properties = true:silent 29 | dotnet_style_object_initializer = true:suggestion 30 | dotnet_style_collection_initializer = true:suggestion 31 | dotnet_style_prefer_simplified_boolean_expressions = true:suggestion 32 | dotnet_style_prefer_conditional_expression_over_assignment = true:silent 33 | dotnet_style_prefer_conditional_expression_over_return = true:silent 34 | dotnet_style_explicit_tuple_names = true:warning 35 | dotnet_style_prefer_inferred_tuple_names = true:suggestion 36 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion 37 | dotnet_style_prefer_compound_assignment = true:suggestion 38 | dotnet_style_prefer_simplified_interpolation = true:suggestion 39 | dotnet_style_namespace_match_folder = true:suggestion 40 | 41 | # New line preferences 42 | csharp_new_line_before_open_brace = all 43 | csharp_new_line_before_else = true 44 | csharp_new_line_before_catch = true 45 | csharp_new_line_before_finally = true 46 | csharp_new_line_before_members_in_object_initializers = true 47 | csharp_new_line_before_members_in_anonymous_types = true 48 | csharp_new_line_between_query_expression_clauses = true 49 | 50 | # Indentation preferences 51 | csharp_indent_block_contents = true 52 | csharp_indent_braces = false 53 | csharp_indent_case_contents = true 54 | csharp_indent_switch_labels = true 55 | csharp_indent_labels = flush_left 56 | 57 | # avoid this. unless absolutely necessary 58 | dotnet_style_qualification_for_field = false:suggestion 59 | dotnet_style_qualification_for_property = false:suggestion 60 | dotnet_style_qualification_for_method = false:suggestion 61 | dotnet_style_qualification_for_event = false:suggestion 62 | 63 | # only use var when it's obvious what the variable type is 64 | csharp_style_var_for_built_in_types = true:suggestion 65 | csharp_style_var_when_type_is_apparent = true:suggestion 66 | csharp_style_var_elsewhere = true:suggestion 67 | 68 | # use language keywords instead of BCL types 69 | dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion 70 | dotnet_style_predefined_type_for_member_access = true:suggestion 71 | 72 | # generic capitalization styles 73 | dotnet_naming_style.pascal_case_style.capitalization = pascal_case 74 | dotnet_naming_style.camel_case_style.capitalization = camel_case 75 | 76 | # private/protected const symbols 77 | dotnet_naming_symbols.constant_fields.applicable_accessibilities = private, protected 78 | dotnet_naming_symbols.constant_fields.applicable_kinds = field 79 | dotnet_naming_symbols.constant_fields.required_modifiers = const 80 | # name all private/protected const fields using camelCase 81 | dotnet_naming_rule.constant_fields_should_be_camel_case.symbols = constant_fields 82 | dotnet_naming_rule.constant_fields_should_be_camel_case.style = camel_case_style 83 | dotnet_naming_rule.constant_fields_should_be_camel_case.severity = suggestion 84 | 85 | # parameter symbols 86 | dotnet_naming_symbols.parameter_symbols.applicable_kinds = parameter 87 | # name all parameter symbols using camelCase 88 | dotnet_naming_rule.parameter_symbols_should_be_camel_case.symbols = parameter_symbols 89 | dotnet_naming_rule.parameter_symbols_should_be_camel_case.style = camel_case_style 90 | dotnet_naming_rule.parameter_symbols_should_be_camel_case.severity = suggestion 91 | 92 | # Classes, namespaces, etc are PascalCase 93 | dotnet_naming_symbols.public_symbols.applicable_kinds = namespace, class, struct, interface, enum, property, method, field, event, delegate, type_parameter, local_function 94 | # name all Classes, namespaces etc using PascalCase 95 | dotnet_naming_rule.public_symbols_should_be_pascal_case.symbols = public_symbols 96 | dotnet_naming_rule.public_symbols_should_be_pascal_case.style = pascal_case_style 97 | dotnet_naming_rule.public_symbols_should_be_pascal_case.severity = suggestion 98 | 99 | # async style 100 | dotnet_naming_style.async_suffix_style.required_suffix = Async 101 | dotnet_naming_style.async_suffix_style.capitalization = pascal_case 102 | # async method symbols 103 | dotnet_naming_symbols.async_methods.required_modifiers = async 104 | dotnet_naming_symbols.async_methods.applicable_kinds = method 105 | dotnet_naming_symbols.async_methods.applicable_accessibilities = * 106 | # name all async methods using async suffix 107 | dotnet_naming_rule.async_methods_should_end_with_async.symbols = async_methods 108 | dotnet_naming_rule.async_methods_should_end_with_async.style = async_suffix_style 109 | dotnet_naming_rule.async_methods_should_end_with_async.severity = suggestion 110 | 111 | # private/protected fields symbols 112 | dotnet_naming_symbols.private_protected_field_symbols.applicable_kinds = field 113 | dotnet_naming_symbols.private_protected_field_symbols.applicable_accessibilities = private, protected 114 | # name all private and protected field symbols using camelCase 115 | dotnet_naming_rule.private_protected_field_symbols_should_be_camel_case.symbols = private_protected_field_symbols 116 | dotnet_naming_rule.private_protected_field_symbols_should_be_camel_case.severity = suggestion 117 | dotnet_naming_rule.private_protected_field_symbols_should_be_camel_case.style = camel_case_style 118 | 119 | # Code style defaults 120 | dotnet_sort_system_directives_first = false 121 | csharp_preserve_single_line_blocks = true 122 | csharp_preserve_single_line_statements = false 123 | 124 | # Expression-level preferences 125 | dotnet_style_object_initializer = true:suggestion 126 | dotnet_style_collection_initializer = true:suggestion 127 | dotnet_style_explicit_tuple_names = true:warning 128 | dotnet_style_coalesce_expression = true:suggestion 129 | dotnet_style_null_propagation = true:suggestion 130 | 131 | # Expression-bodied members 132 | csharp_style_expression_bodied_methods = true:suggestion 133 | csharp_style_expression_bodied_constructors = true:suggestion 134 | csharp_style_expression_bodied_operators = true:suggestion 135 | csharp_style_expression_bodied_properties = true:suggestion 136 | csharp_style_expression_bodied_indexers = true:suggestion 137 | csharp_style_expression_bodied_accessors = true:suggestion 138 | 139 | # Pattern matching 140 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion 141 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion 142 | csharp_style_inlined_variable_declaration = true:suggestion 143 | 144 | # Null checking preferences 145 | csharp_style_throw_expression = true:suggestion 146 | csharp_style_conditional_delegate_call = true:suggestion 147 | 148 | # Space preferences 149 | csharp_space_after_cast = false 150 | csharp_space_after_colon_in_inheritance_clause = true 151 | csharp_space_after_comma = true 152 | csharp_space_after_dot = false 153 | csharp_space_after_keywords_in_control_flow_statements = true 154 | csharp_space_after_semicolon_in_for_statement = true 155 | csharp_space_around_binary_operators = before_and_after 156 | csharp_space_around_declaration_statements = do_not_ignore 157 | csharp_space_before_colon_in_inheritance_clause = true 158 | csharp_space_before_comma = false 159 | csharp_space_before_dot = false 160 | csharp_space_before_open_square_brackets = false 161 | csharp_space_before_semicolon_in_for_statement = false 162 | csharp_space_between_empty_square_brackets = false 163 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 164 | csharp_space_between_method_call_name_and_opening_parenthesis = false 165 | csharp_space_between_method_call_parameter_list_parentheses = false 166 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 167 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 168 | csharp_space_between_method_declaration_parameter_list_parentheses = false 169 | csharp_space_between_parentheses = false 170 | csharp_space_between_square_brackets = false 171 | csharp_using_directive_placement = outside_namespace:silent 172 | csharp_prefer_simple_using_statement = true:suggestion 173 | csharp_prefer_braces = true:silent 174 | csharp_style_namespace_declarations = block_scoped:silent 175 | csharp_style_expression_bodied_lambdas = true:silent 176 | csharp_style_expression_bodied_local_functions = false:silent 177 | csharp_style_prefer_null_check_over_type_check = true:suggestion 178 | csharp_prefer_simple_default_expression = true:suggestion 179 | csharp_style_prefer_local_over_anonymous_function = true:suggestion 180 | csharp_style_prefer_index_operator = true:suggestion 181 | csharp_style_prefer_range_operator = true:suggestion 182 | csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion 183 | 184 | # IDE1006: Naming Styles 185 | #dotnet_diagnostic.IDE1006.severity = silent 186 | 187 | # CA1710: Identifiers should have correct suffix 188 | #dotnet_diagnostic.CA1710.severity = none 189 | -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | # yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json 2 | 3 | name: .NET 4 | 5 | on: 6 | workflow_dispatch: 7 | push: 8 | branches: [main] 9 | paths-ignore: 10 | - "*.md" 11 | - "*.txt" 12 | - .editorconfig 13 | - ".github/**" 14 | - .gitignore 15 | pull_request: 16 | branches: [main] 17 | 18 | jobs: 19 | build: 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Setup .NET 25 | uses: actions/setup-dotnet@v1 26 | with: 27 | dotnet-version: 6.0.x 28 | - name: Restore dependencies 29 | run: dotnet restore 30 | - name: Build 31 | run: dotnet build --no-restore 32 | - name: Test 33 | run: dotnet test --no-build --verbosity normal 34 | - name: Create nupkg 35 | run: dotnet pack --configuration Release --version-suffix $GITHUB_RUN_NUMBER ./src/SourceInject/ 36 | - name: Publish nupkg 37 | if: ${{ github.event_name != 'pull_request' }} 38 | env: 39 | NUGET_AUTH_TOKEN: ${{secrets.NUGET_AUTH_TOKEN}} 40 | run: dotnet nuget push --api-key $NUGET_AUTH_TOKEN --source https://api.nuget.org/v3/index.json ./src/SourceInject/bin/Release/*.nupkg 41 | -------------------------------------------------------------------------------- /.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 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.vspscc 94 | *.vssscc 95 | .builds 96 | *.pidb 97 | *.svclog 98 | *.scc 99 | 100 | # Chutzpah Test files 101 | _Chutzpah* 102 | 103 | # Visual C++ cache files 104 | ipch/ 105 | *.aps 106 | *.ncb 107 | *.opendb 108 | *.opensdf 109 | *.sdf 110 | *.cachefile 111 | *.VC.db 112 | *.VC.VC.opendb 113 | 114 | # Visual Studio profiler 115 | *.psess 116 | *.vsp 117 | *.vspx 118 | *.sap 119 | 120 | # Visual Studio Trace Files 121 | *.e2e 122 | 123 | # TFS 2012 Local Workspace 124 | $tf/ 125 | 126 | # Guidance Automation Toolkit 127 | *.gpState 128 | 129 | # ReSharper is a .NET coding add-in 130 | _ReSharper*/ 131 | *.[Rr]e[Ss]harper 132 | *.DotSettings.user 133 | 134 | # TeamCity is a build add-in 135 | _TeamCity* 136 | 137 | # DotCover is a Code Coverage Tool 138 | *.dotCover 139 | 140 | # AxoCover is a Code Coverage Tool 141 | .axoCover/* 142 | !.axoCover/settings.json 143 | 144 | # Coverlet is a free, cross platform Code Coverage Tool 145 | coverage*.json 146 | coverage*.xml 147 | coverage*.info 148 | 149 | # Visual Studio code coverage results 150 | *.coverage 151 | *.coveragexml 152 | 153 | # NCrunch 154 | _NCrunch_* 155 | .*crunch*.local.xml 156 | nCrunchTemp_* 157 | 158 | # MightyMoose 159 | *.mm.* 160 | AutoTest.Net/ 161 | 162 | # Web workbench (sass) 163 | .sass-cache/ 164 | 165 | # Installshield output folder 166 | [Ee]xpress/ 167 | 168 | # DocProject is a documentation generator add-in 169 | DocProject/buildhelp/ 170 | DocProject/Help/*.HxT 171 | DocProject/Help/*.HxC 172 | DocProject/Help/*.hhc 173 | DocProject/Help/*.hhk 174 | DocProject/Help/*.hhp 175 | DocProject/Help/Html2 176 | DocProject/Help/html 177 | 178 | # Click-Once directory 179 | publish/ 180 | 181 | # Publish Web Output 182 | *.[Pp]ublish.xml 183 | *.azurePubxml 184 | # Note: Comment the next line if you want to checkin your web deploy settings, 185 | # but database connection strings (with potential passwords) will be unencrypted 186 | *.pubxml 187 | *.publishproj 188 | 189 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 190 | # checkin your Azure Web App publish settings, but sensitive information contained 191 | # in these scripts will be unencrypted 192 | PublishScripts/ 193 | 194 | # NuGet Packages 195 | *.nupkg 196 | # NuGet Symbol Packages 197 | *.snupkg 198 | # The packages folder can be ignored because of Package Restore 199 | **/[Pp]ackages/* 200 | # except build/, which is used as an MSBuild target. 201 | !**/[Pp]ackages/build/ 202 | # Uncomment if necessary however generally it will be regenerated when needed 203 | #!**/[Pp]ackages/repositories.config 204 | # NuGet v3's project.json files produces more ignorable files 205 | *.nuget.props 206 | *.nuget.targets 207 | 208 | # Microsoft Azure Build Output 209 | csx/ 210 | *.build.csdef 211 | 212 | # Microsoft Azure Emulator 213 | ecf/ 214 | rcf/ 215 | 216 | # Windows Store app package directories and files 217 | AppPackages/ 218 | BundleArtifacts/ 219 | Package.StoreAssociation.xml 220 | _pkginfo.txt 221 | *.appx 222 | *.appxbundle 223 | *.appxupload 224 | 225 | # Visual Studio cache files 226 | # files ending in .cache can be ignored 227 | *.[Cc]ache 228 | # but keep track of directories ending in .cache 229 | !?*.[Cc]ache/ 230 | 231 | # Others 232 | ClientBin/ 233 | ~$* 234 | *~ 235 | *.dbmdl 236 | *.dbproj.schemaview 237 | *.jfm 238 | *.pfx 239 | *.publishsettings 240 | orleans.codegen.cs 241 | 242 | # Including strong name files can present a security risk 243 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 244 | #*.snk 245 | 246 | # Since there are multiple workflows, uncomment next line to ignore bower_components 247 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 248 | #bower_components/ 249 | 250 | # RIA/Silverlight projects 251 | Generated_Code/ 252 | 253 | # Backup & report files from converting an old project file 254 | # to a newer Visual Studio version. Backup files are not needed, 255 | # because we have git ;-) 256 | _UpgradeReport_Files/ 257 | Backup*/ 258 | UpgradeLog*.XML 259 | UpgradeLog*.htm 260 | ServiceFabricBackup/ 261 | *.rptproj.bak 262 | 263 | # SQL Server files 264 | *.mdf 265 | *.ldf 266 | *.ndf 267 | 268 | # Business Intelligence projects 269 | *.rdl.data 270 | *.bim.layout 271 | *.bim_*.settings 272 | *.rptproj.rsuser 273 | *- [Bb]ackup.rdl 274 | *- [Bb]ackup ([0-9]).rdl 275 | *- [Bb]ackup ([0-9][0-9]).rdl 276 | 277 | # Microsoft Fakes 278 | FakesAssemblies/ 279 | 280 | # GhostDoc plugin setting file 281 | *.GhostDoc.xml 282 | 283 | # Node.js Tools for Visual Studio 284 | .ntvs_analysis.dat 285 | node_modules/ 286 | 287 | # Visual Studio 6 build log 288 | *.plg 289 | 290 | # Visual Studio 6 workspace options file 291 | *.opt 292 | 293 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 294 | *.vbw 295 | 296 | # Visual Studio LightSwitch build output 297 | **/*.HTMLClient/GeneratedArtifacts 298 | **/*.DesktopClient/GeneratedArtifacts 299 | **/*.DesktopClient/ModelManifest.xml 300 | **/*.Server/GeneratedArtifacts 301 | **/*.Server/ModelManifest.xml 302 | _Pvt_Extensions 303 | 304 | # Paket dependency manager 305 | .paket/paket.exe 306 | paket-files/ 307 | 308 | # FAKE - F# Make 309 | .fake/ 310 | 311 | # CodeRush personal settings 312 | .cr/personal 313 | 314 | # Python Tools for Visual Studio (PTVS) 315 | __pycache__/ 316 | *.pyc 317 | 318 | # Cake - Uncomment if you are using it 319 | # tools/** 320 | # !tools/packages.config 321 | 322 | # Tabs Studio 323 | *.tss 324 | 325 | # Telerik's JustMock configuration file 326 | *.jmconfig 327 | 328 | # BizTalk build output 329 | *.btp.cs 330 | *.btm.cs 331 | *.odx.cs 332 | *.xsd.cs 333 | 334 | # OpenCover UI analysis results 335 | OpenCover/ 336 | 337 | # Azure Stream Analytics local run output 338 | ASALocalRun/ 339 | 340 | # MSBuild Binary and Structured Log 341 | *.binlog 342 | 343 | # NVidia Nsight GPU debugger configuration file 344 | *.nvuser 345 | 346 | # MFractors (Xamarin productivity tool) working folder 347 | .mfractor/ 348 | 349 | # Local History for Visual Studio 350 | .localhistory/ 351 | 352 | # BeatPulse healthcheck temp database 353 | healthchecksdb 354 | 355 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 356 | MigrationBackup/ 357 | 358 | # Ionide (cross platform F# VS Code tools) working folder 359 | .ionide/ 360 | 361 | # Fody - auto-generated XML schema 362 | FodyWeavers.xsd 363 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) Giovanni Bassi. All rights reserved. 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Source Inject 2 | 3 | A source generator for C# that uses [Roslyn](https://github.com/dotnet/roslyn) (the C# compiler) to allow you to generate 4 | your dependencies injection during compile time. By doing this 5 | you avoid using reflection and services are automatically 6 | registered. 7 | 8 | [![NuGet version (sourceinject)](https://img.shields.io/nuget/v/sourceinject?color=blue)](https://www.nuget.org/packages/sourceinject/) 9 | [![Build](https://github.com/giggio/sourceinject/actions/workflows/dotnet.yml/badge.svg)](https://github.com/giggio/sourceinject/actions/workflows/dotnet.yml) 10 | [![License](https://img.shields.io/github/license/giggio/sourceinject.svg)](https://github.com/giggio/sourceinject/blob/master/LICENSE.txt) 11 | 12 | ## How to use it 13 | 14 | Install it and add an attribute to the classes you want injected in your service provider, like so: 15 | 16 | ```csharp 17 | [Inject] 18 | public class ExampleService 19 | { 20 | private readonly AnotherService anotherService; 21 | 22 | public ExampleService(AnotherService anotherService) => 23 | this.anotherService = anotherService; 24 | 25 | public string GetValue() => anotherService.Value; 26 | } 27 | 28 | [Inject(ServiceLifetime.Singleton)] 29 | public class AnotherService 30 | { 31 | public string Value => "Hello World!"; 32 | } 33 | ``` 34 | 35 | As you can see above you can define the lifetime. The default lifetime is transient. 36 | You can also use the following attributes: 37 | 38 | - `InjectSingletonAttribute` 39 | - `InjectScopedAttribute` 40 | - `InjectTransientAttribute` 41 | 42 | The last one is the same as using `Inject` without any arguments. 43 | 44 | You then have to call the `Discover` method so these classes are found and the source is generated. 45 | You can then require them using constructor injection or service locator, for example: 46 | 47 | ```csharp 48 | var services = new ServiceCollection(); 49 | services.Discover(); 50 | var serviceProvider = services.BuildServiceProvider(); 51 | var exampleService = serviceProvider.GetRequiredService(); 52 | ``` 53 | 54 | You can also discover services in other assemblies. To be able to do this you have to call 55 | the method `DiscoverIn` or `Discoverer.Discover(services)`. If your 56 | assembly name has dots `.` in them they will be replaced by underscore `_`. 57 | 58 | All these methods (`Discover` et all) and attributes will be generated in your project for you. 59 | 60 | You can see the generated code using Visual Studio. See [here](https://docs.microsoft.com/en-us/visualstudio/releases/2019/media/16.9/16.9_p3_source_generators_node.png) for an example. 61 | 62 | ## Installing 63 | 64 | The package is available ([on NuGet](https://www.nuget.org/packages/sourceinject). 65 | To install from the command line: 66 | 67 | ```shell 68 | dotnet add package sourceinject 69 | ``` 70 | 71 | Or use the Package Manager in Visual Studio. 72 | 73 | ## Contributing 74 | 75 | The main supported IDE for development is Visual Studio 2019. 76 | 77 | Questions, comments, bug reports, and pull requests are all welcome. 78 | Bug reports that include steps to reproduce (including code) are 79 | preferred. Even better, make them in the form of pull requests. 80 | Before you start to work on an existing issue, check if it is not assigned 81 | to anyone yet, and if it is, talk to that person. 82 | 83 | ## Maintainers/Core team 84 | 85 | - [Giovanni Bassi](http://blog.lambda3.com.br/L3/giovannibassi/), aka Giggio, 86 | [Lambda3](http://www.lambda3.com.br), [@giovannibassi](https://twitter.com/giovannibassi) 87 | 88 | Contributors can be found at the [contributors](https://github.com/giggio/sourceinject/graphs/contributors) page on Github. 89 | 90 | ## License 91 | 92 | This software is open source, licensed under the MIT License. 93 | See [LICENSE](https://github.com/giggio/sourceinject/blob/master/LICENSE) for details. 94 | Check out the terms of the license before you contribute, fork, copy or do anything 95 | with the code. If you decide to contribute you agree to grant copyright of all your contribution to this project and agree to 96 | mention clearly if do not agree to these terms. Your work will be licensed with the project at MIT, along the rest of the code. 97 | -------------------------------------------------------------------------------- /SourceInject.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31025.194 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{1456ACC0-61E1-4720-AFF6-70633E4CB083}" 7 | ProjectSection(SolutionItems) = preProject 8 | .editorconfig = .editorconfig 9 | .gitignore = .gitignore 10 | LICENSE = LICENSE 11 | README.md = README.md 12 | EndProjectSection 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{559D7005-0873-4DAB-962C-37D8B81319A2}" 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{4A1CD940-EA03-4F0E-AC09-508520CE1896}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SourceInject", "src\SourceInject\SourceInject.csproj", "{F0412F0C-6FCD-4552-BD04-45F2B0F1668F}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SourceInjectTests", "test\SourceInjectTests\SourceInjectTests.csproj", "{A0EE3A74-0E98-41AB-B38A-B4741CFD591C}" 21 | EndProject 22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleApp", "test\ConsoleApp\ConsoleApp.csproj", "{856A5373-59B8-41DC-943E-4F840389B13D}" 23 | EndProject 24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lib", "test\Lib\Lib.csproj", "{3E4FC6A8-2FB3-47E1-9486-D03043492ADA}" 25 | EndProject 26 | Global 27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 28 | Debug|Any CPU = Debug|Any CPU 29 | Release|Any CPU = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 32 | {F0412F0C-6FCD-4552-BD04-45F2B0F1668F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {F0412F0C-6FCD-4552-BD04-45F2B0F1668F}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {F0412F0C-6FCD-4552-BD04-45F2B0F1668F}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {F0412F0C-6FCD-4552-BD04-45F2B0F1668F}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {A0EE3A74-0E98-41AB-B38A-B4741CFD591C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {A0EE3A74-0E98-41AB-B38A-B4741CFD591C}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {A0EE3A74-0E98-41AB-B38A-B4741CFD591C}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {A0EE3A74-0E98-41AB-B38A-B4741CFD591C}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {856A5373-59B8-41DC-943E-4F840389B13D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {856A5373-59B8-41DC-943E-4F840389B13D}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {856A5373-59B8-41DC-943E-4F840389B13D}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {856A5373-59B8-41DC-943E-4F840389B13D}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {3E4FC6A8-2FB3-47E1-9486-D03043492ADA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {3E4FC6A8-2FB3-47E1-9486-D03043492ADA}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {3E4FC6A8-2FB3-47E1-9486-D03043492ADA}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {3E4FC6A8-2FB3-47E1-9486-D03043492ADA}.Release|Any CPU.Build.0 = Release|Any CPU 48 | EndGlobalSection 49 | GlobalSection(SolutionProperties) = preSolution 50 | HideSolutionNode = FALSE 51 | EndGlobalSection 52 | GlobalSection(NestedProjects) = preSolution 53 | {F0412F0C-6FCD-4552-BD04-45F2B0F1668F} = {4A1CD940-EA03-4F0E-AC09-508520CE1896} 54 | {A0EE3A74-0E98-41AB-B38A-B4741CFD591C} = {559D7005-0873-4DAB-962C-37D8B81319A2} 55 | {856A5373-59B8-41DC-943E-4F840389B13D} = {559D7005-0873-4DAB-962C-37D8B81319A2} 56 | {3E4FC6A8-2FB3-47E1-9486-D03043492ADA} = {559D7005-0873-4DAB-962C-37D8B81319A2} 57 | EndGlobalSection 58 | GlobalSection(ExtensibilityGlobals) = postSolution 59 | SolutionGuid = {A2AEB76C-782C-480D-9579-3C3BB0F20B2E} 60 | EndGlobalSection 61 | EndGlobal 62 | -------------------------------------------------------------------------------- /src/SourceInject/Generator.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp.Syntax; 3 | using Microsoft.CodeAnalysis.Text; 4 | using System; 5 | using System.Collections.Immutable; 6 | using System.Linq; 7 | using System.Text; 8 | 9 | namespace SourceInject; 10 | 11 | [Generator] 12 | public class Generator : ISourceGenerator 13 | { 14 | public void Initialize(GeneratorInitializationContext context) 15 | { 16 | const string attribute = @"// 17 | using Microsoft.Extensions.DependencyInjection; 18 | [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 19 | internal class InjectAttribute : System.Attribute 20 | { 21 | internal InjectAttribute(ServiceLifetime serviceLifetime = ServiceLifetime.Transient) { } 22 | } 23 | [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 24 | internal class InjectSingletonAttribute : System.Attribute 25 | { 26 | } 27 | [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 28 | internal class InjectScopedAttribute : System.Attribute 29 | { 30 | } 31 | [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 32 | internal class InjectTransientAttribute : System.Attribute 33 | { 34 | } 35 | "; 36 | context.RegisterForPostInitialization(context => context.AddSource("Inject.Generated.cs", SourceText.From(attribute, Encoding.UTF8))); 37 | context.RegisterForSyntaxNotifications(() => new ServicesReceiver()); 38 | } 39 | 40 | public void Execute(GeneratorExecutionContext context) 41 | { 42 | var receiver = (ServicesReceiver?)context.SyntaxReceiver; 43 | if (receiver == null || !receiver.ClassesToRegister.Any()) 44 | return; 45 | var registrations = new StringBuilder(); 46 | const string spaces = " "; 47 | foreach (var clazz in receiver.ClassesToRegister) 48 | { 49 | var semanticModel = context.Compilation.GetSemanticModel(clazz.SyntaxTree); 50 | if (semanticModel == null) 51 | continue; 52 | var symbol = semanticModel.GetDeclaredSymbol(clazz); 53 | if (symbol == null) 54 | return; 55 | var lifetime = GetLifetime(symbol.GetAttributes()); 56 | switch (lifetime) 57 | { 58 | case Lifetime.Singleton: 59 | registrations.Append(spaces); 60 | registrations.AppendLine($"services.AddSingleton<{symbol.ToDisplayString(qualifiedFormat)}>();"); 61 | break; 62 | case Lifetime.Scoped: 63 | registrations.Append(spaces); 64 | registrations.AppendLine($"services.AddScoped<{symbol.ToDisplayString(qualifiedFormat)}>();"); 65 | break; 66 | case Lifetime.Transient: 67 | registrations.Append(spaces); 68 | registrations.AppendLine($"services.AddTransient<{symbol.ToDisplayString(qualifiedFormat)}>();"); 69 | break; 70 | default: 71 | break; 72 | } 73 | foreach (var interf in ((ITypeSymbol)symbol).AllInterfaces) 74 | { 75 | switch (lifetime) 76 | { 77 | case Lifetime.Singleton: 78 | registrations.Append(spaces); 79 | registrations.AppendLine($"services.AddSingleton<{interf.ToDisplayString(qualifiedFormat)}, {symbol.ToDisplayString(qualifiedFormat)}>();"); 80 | break; 81 | case Lifetime.Scoped: 82 | registrations.Append(spaces); 83 | registrations.AppendLine($"services.AddScoped<{interf.ToDisplayString(qualifiedFormat)}, {symbol.ToDisplayString(qualifiedFormat)}>();"); 84 | break; 85 | case Lifetime.Transient: 86 | registrations.Append(spaces); 87 | registrations.AppendLine($"services.AddTransient<{interf.ToDisplayString(qualifiedFormat)}, {symbol.ToDisplayString(qualifiedFormat)}>();"); 88 | break; 89 | default: 90 | break; 91 | } 92 | 93 | } 94 | } 95 | 96 | 97 | ISymbol? methodSymbol = null; 98 | if (receiver.InvocationSyntaxNode != null) 99 | { 100 | 101 | var invocationSemanticModel = context.Compilation.GetSemanticModel(receiver.InvocationSyntaxNode.SyntaxTree); 102 | var methodSyntax = receiver.InvocationSyntaxNode.FirstAncestorOrSelf(); 103 | methodSymbol = methodSyntax == null ? null : invocationSemanticModel.GetDeclaredSymbol(methodSyntax); 104 | } 105 | 106 | if (context.Compilation.AssemblyName == null) 107 | return; 108 | var safeAssemblyName = context.Compilation.AssemblyName.Replace(".", "_"); 109 | var extensionCode = $@" 110 | public static class GeneratedServicesExtension 111 | {{ 112 | public static void DiscoverIn{safeAssemblyName}(this IServiceCollection services) => services.Discover(); 113 | internal static void Discover(this IServiceCollection services) 114 | {{ 115 | {registrations} }} 116 | }}"; 117 | if (methodSymbol == null || methodSymbol.ContainingNamespace.IsGlobalNamespace) 118 | { 119 | var newClassCodeBuilder = new StringBuilder(); 120 | foreach (var line in extensionCode.Split(new[] { @" 121 | " }, StringSplitOptions.None)) 122 | { 123 | if (line.Length > 4 && line.Substring(0, 4) == " ") 124 | newClassCodeBuilder.AppendLine(line.Substring(4, line.Length - 4)); 125 | else 126 | newClassCodeBuilder.AppendLine(line); 127 | } 128 | extensionCode = newClassCodeBuilder.ToString(); 129 | } 130 | else 131 | { 132 | var ns = methodSymbol.ContainingNamespace.Name.ToString(); 133 | extensionCode = $@"using {ns}; 134 | 135 | namespace {ns} 136 | {{{extensionCode} 137 | }} 138 | "; 139 | } 140 | var discovererCode = $@" 141 | public static class {safeAssemblyName}Discoverer 142 | {{ 143 | public static void Discover(IServiceCollection services) => services.Discover(); 144 | }} 145 | "; 146 | var finalCode = @"// 147 | using Microsoft.Extensions.DependencyInjection; 148 | " + extensionCode + discovererCode; 149 | context.AddSource("GeneratedServicesExtension.Generated.cs", SourceText.From(finalCode, Encoding.UTF8)); 150 | } 151 | 152 | private static Lifetime GetLifetime(IImmutableList attributes) 153 | { 154 | if (attributes.Any(a => a.AttributeClass?.Name == "InjectSingletonAttribute")) 155 | return Lifetime.Singleton; 156 | if (attributes.Any(a => a.AttributeClass?.Name == "InjectScopedAttribute")) 157 | return Lifetime.Scoped; 158 | if (attributes.Any(a => a.AttributeClass?.Name == "InjectTransientAttribute")) 159 | return Lifetime.Transient; 160 | var injectAttribute = attributes.FirstOrDefault(a => a.AttributeClass?.Name == "InjectAttribute"); 161 | if (injectAttribute == null) 162 | return Lifetime.None; 163 | var injectArg = injectAttribute.ConstructorArguments.FirstOrDefault(); 164 | if (injectArg.IsNull || injectArg.Kind != TypedConstantKind.Enum || injectArg.Type?.ToString() != "Microsoft.Extensions.DependencyInjection.ServiceLifetime") 165 | return Lifetime.None; 166 | return injectArg.Value switch 167 | { 168 | 1 => Lifetime.Scoped, 169 | 2 => Lifetime.Transient, 170 | // 0 (singleton) or others 171 | _ => Lifetime.Singleton, 172 | }; 173 | } 174 | 175 | private static readonly SymbolDisplayFormat qualifiedFormat = new(globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, 176 | typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, 177 | genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, 178 | miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); 179 | 180 | enum Lifetime 181 | { 182 | None, Singleton, Scoped, Transient 183 | } 184 | } 185 | 186 | 187 | -------------------------------------------------------------------------------- /src/SourceInject/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "SourceInject": { 4 | "commandName": "DebugRoslynComponent", 5 | "targetProject": "..\\..\\test\\ConsoleApp\\ConsoleApp.csproj" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /src/SourceInject/ServicesReceiver.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp.Syntax; 3 | using System.Collections.Generic; 4 | 5 | namespace SourceInject; 6 | 7 | internal class ServicesReceiver : ISyntaxReceiver 8 | { 9 | public List ClassesToRegister { get; } = new(); 10 | public InvocationExpressionSyntax? InvocationSyntaxNode { get; private set; } 11 | 12 | public void OnVisitSyntaxNode(SyntaxNode syntaxNode) 13 | { 14 | if (syntaxNode is ClassDeclarationSyntax cds) 15 | ClassesToRegister.Add(cds); 16 | 17 | if (syntaxNode is InvocationExpressionSyntax 18 | { 19 | Expression: MemberAccessExpressionSyntax 20 | { 21 | Name.Identifier.ValueText: "Discover" 22 | } 23 | } invocationSyntax) 24 | { 25 | InvocationSyntaxNode = invocationSyntax; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/SourceInject/SourceInject.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.0 4 | latest 5 | enable 6 | SourceInject 7 | 0 8 | 0.1.$(VersionSuffix) 9 | Giovanni Bassi 10 | A source generator for C# that uses Roslyn (the C# compiler) to allow you to generate your dependencies injection during compile time. 11 | https://github.com/giggio/sourceinject.git 12 | git 13 | source generator 14 | https://github.com/giggio/sourceinject 15 | (c) Giovanni Bassi 16 | MIT 17 | false 18 | true 19 | true 20 | true 21 | 22 | 23 | 24 | 25 | 26 | 27 | all 28 | runtime; build; native; contentfiles; analyzers; buildtransitive 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /test/ConsoleApp/ConsoleApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | net6.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /test/ConsoleApp/ExampleService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace ConsoleApp; 4 | 5 | [Inject] 6 | public class ExampleService 7 | { 8 | private readonly AnotherService anotherService; 9 | 10 | public ExampleService(AnotherService anotherService) => 11 | this.anotherService = anotherService; 12 | 13 | public string GetValue() => anotherService.Value; 14 | } 15 | 16 | public interface IAnotherService 17 | { 18 | string Value { get; } 19 | } 20 | 21 | [Inject(ServiceLifetime.Singleton)] 22 | public class AnotherService : IAnotherService 23 | { 24 | public string Value => "Hello World!"; 25 | } 26 | 27 | interface IGeneric { } 28 | interface IGeneric : IGeneric { } 29 | [InjectTransient] 30 | class C : IGeneric { } 31 | -------------------------------------------------------------------------------- /test/ConsoleApp/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using static System.Console; 3 | 4 | var services = new ServiceCollection(); 5 | services.Discover(); 6 | services.DiscoverInLib(); 7 | var serviceProvider = services.BuildServiceProvider(); 8 | var exampleService = serviceProvider.GetRequiredService(); 9 | WriteLine(exampleService.GetValue()); 10 | var serviceOnLib = serviceProvider.GetRequiredService(); 11 | WriteLine(serviceOnLib.Value); 12 | 13 | -------------------------------------------------------------------------------- /test/Lib/Lib.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net6.0 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /test/Lib/ServiceOnLib.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace Lib; 4 | 5 | [Inject(ServiceLifetime.Singleton)] 6 | public class ServiceOnLib 7 | { 8 | #pragma warning disable CA1822 // Mark members as static 9 | public string Value => "Hello from Lib!"; 10 | #pragma warning restore CA1822 // Mark members as static 11 | } 12 | -------------------------------------------------------------------------------- /test/SourceInjectTests/GeneratorTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using Microsoft.CodeAnalysis.CSharp; 3 | using Shouldly; 4 | using SourceInject; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.Linq; 9 | using Xunit; 10 | using Xunit.Abstractions; 11 | 12 | namespace SourceInjectTests; 13 | 14 | public class GeneratorTests 15 | { 16 | private readonly ITestOutputHelper output; 17 | 18 | public GeneratorTests(ITestOutputHelper output) => this.output = output ?? throw new ArgumentNullException(nameof(output)); 19 | 20 | [Fact] 21 | public void GeneratedCodeWithoutServicesWork() 22 | { 23 | var source = @" 24 | using Microsoft.Extensions.DependencyInjection; 25 | namespace WebApp 26 | { 27 | class C 28 | { 29 | void M(IServiceCollection services) 30 | { 31 | services.Discover(); 32 | } 33 | } 34 | }"; 35 | var (attributeCode, extensionCode) = GetGeneratedOutput(source); 36 | attributeCode.ShouldNotBeNull(); 37 | extensionCode.ShouldNotBeNull(); 38 | 39 | const string expectedAttributeCode = @"// 40 | using Microsoft.Extensions.DependencyInjection; 41 | [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 42 | internal class InjectAttribute : System.Attribute 43 | { 44 | internal InjectAttribute(ServiceLifetime serviceLifetime = ServiceLifetime.Transient) { } 45 | } 46 | [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 47 | internal class InjectSingletonAttribute : System.Attribute 48 | { 49 | } 50 | [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 51 | internal class InjectScopedAttribute : System.Attribute 52 | { 53 | } 54 | [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 55 | internal class InjectTransientAttribute : System.Attribute 56 | { 57 | } 58 | "; 59 | const string expectedExtensionCode = @"// 60 | using Microsoft.Extensions.DependencyInjection; 61 | using WebApp; 62 | 63 | namespace WebApp 64 | { 65 | public static class GeneratedServicesExtension 66 | { 67 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 68 | internal static void Discover(this IServiceCollection services) 69 | { 70 | } 71 | } 72 | } 73 | 74 | public static class FooDiscoverer 75 | { 76 | public static void Discover(IServiceCollection services) => services.Discover(); 77 | } 78 | "; 79 | attributeCode.ShouldBe(expectedAttributeCode); 80 | extensionCode.ShouldBe(expectedExtensionCode); 81 | } 82 | 83 | [Fact] 84 | public void GeneratedCodeWithOneService() 85 | { 86 | var source = @" 87 | using Microsoft.Extensions.DependencyInjection; 88 | 89 | namespace WebApp 90 | { 91 | class C 92 | { 93 | void M(IServiceCollection services) 94 | { 95 | services.Discover(); 96 | } 97 | } 98 | [Inject] 99 | class MyService 100 | { 101 | } 102 | }"; 103 | var (_, extensionCode) = GetGeneratedOutput(source); 104 | extensionCode.ShouldNotBeNull(); 105 | 106 | const string expectedExtensionCode = @"// 107 | using Microsoft.Extensions.DependencyInjection; 108 | using WebApp; 109 | 110 | namespace WebApp 111 | { 112 | public static class GeneratedServicesExtension 113 | { 114 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 115 | internal static void Discover(this IServiceCollection services) 116 | { 117 | services.AddTransient(); 118 | } 119 | } 120 | } 121 | 122 | public static class FooDiscoverer 123 | { 124 | public static void Discover(IServiceCollection services) => services.Discover(); 125 | } 126 | "; 127 | extensionCode.ShouldBe(expectedExtensionCode); 128 | } 129 | 130 | [Fact] 131 | public void GeneratedCodeWithTwoServices() 132 | { 133 | var source = @" 134 | using Microsoft.Extensions.DependencyInjection; 135 | 136 | namespace WebApp 137 | { 138 | class C 139 | { 140 | void M(IServiceCollection services) 141 | { 142 | services.Discover(); 143 | } 144 | } 145 | [Inject] 146 | class MyService1 147 | { 148 | } 149 | [Inject] 150 | class MyService2 151 | { 152 | } 153 | }"; 154 | var (_, extensionCode) = GetGeneratedOutput(source); 155 | extensionCode.ShouldNotBeNull(); 156 | 157 | const string expectedExtensionCode = @"// 158 | using Microsoft.Extensions.DependencyInjection; 159 | using WebApp; 160 | 161 | namespace WebApp 162 | { 163 | public static class GeneratedServicesExtension 164 | { 165 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 166 | internal static void Discover(this IServiceCollection services) 167 | { 168 | services.AddTransient(); 169 | services.AddTransient(); 170 | } 171 | } 172 | } 173 | 174 | public static class FooDiscoverer 175 | { 176 | public static void Discover(IServiceCollection services) => services.Discover(); 177 | } 178 | "; 179 | extensionCode.ShouldBe(expectedExtensionCode); 180 | } 181 | 182 | [Fact] 183 | public void GeneratedCodeWithDifferentNamespace() 184 | { 185 | var source = @" 186 | using Microsoft.Extensions.DependencyInjection; 187 | 188 | namespace MyNamespace 189 | { 190 | class C 191 | { 192 | void M(IServiceCollection services) 193 | { 194 | services.Discover(); 195 | } 196 | } 197 | [Inject] 198 | class MyService 199 | { 200 | } 201 | }"; 202 | var (_, extensionCode) = GetGeneratedOutput(source); 203 | extensionCode.ShouldNotBeNull(); 204 | 205 | const string expectedExtensionCode = @"// 206 | using Microsoft.Extensions.DependencyInjection; 207 | using MyNamespace; 208 | 209 | namespace MyNamespace 210 | { 211 | public static class GeneratedServicesExtension 212 | { 213 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 214 | internal static void Discover(this IServiceCollection services) 215 | { 216 | services.AddTransient(); 217 | } 218 | } 219 | } 220 | 221 | public static class FooDiscoverer 222 | { 223 | public static void Discover(IServiceCollection services) => services.Discover(); 224 | } 225 | "; 226 | expectedExtensionCode.ShouldBe(extensionCode); 227 | } 228 | 229 | [Fact] 230 | public void GeneratedCodeWithoutNamespace() 231 | { 232 | var source = @" 233 | using Microsoft.Extensions.DependencyInjection; 234 | class C 235 | { 236 | void M(IServiceCollection services) 237 | { 238 | services.Discover(); 239 | } 240 | } 241 | [Inject] 242 | class MyService 243 | { 244 | }"; 245 | var (_, extensionCode) = GetGeneratedOutput(source); 246 | extensionCode.ShouldNotBeNull(); 247 | 248 | const string expectedExtensionCode = @"// 249 | using Microsoft.Extensions.DependencyInjection; 250 | 251 | public static class GeneratedServicesExtension 252 | { 253 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 254 | internal static void Discover(this IServiceCollection services) 255 | { 256 | services.AddTransient(); 257 | } 258 | } 259 | 260 | public static class FooDiscoverer 261 | { 262 | public static void Discover(IServiceCollection services) => services.Discover(); 263 | } 264 | "; 265 | extensionCode.ShouldBe(expectedExtensionCode); 266 | } 267 | 268 | [Fact] 269 | public void GeneratedCodeWithTopLevelStatement() 270 | { 271 | var source = @" 272 | using Microsoft.Extensions.DependencyInjection; 273 | var services = new ServiceCollection(); 274 | services.Discover(); 275 | var serviceProvider = services.BuildServiceProvider(); 276 | [Inject] 277 | class MyService 278 | { 279 | }"; 280 | var (_, extensionCode) = GetGeneratedOutput(source, true); 281 | extensionCode.ShouldNotBeNull(); 282 | 283 | const string expectedExtensionCode = @"// 284 | using Microsoft.Extensions.DependencyInjection; 285 | 286 | public static class GeneratedServicesExtension 287 | { 288 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 289 | internal static void Discover(this IServiceCollection services) 290 | { 291 | services.AddTransient(); 292 | } 293 | } 294 | 295 | public static class FooDiscoverer 296 | { 297 | public static void Discover(IServiceCollection services) => services.Discover(); 298 | } 299 | "; 300 | extensionCode.ShouldBe(expectedExtensionCode); 301 | } 302 | 303 | [Fact] 304 | public void GeneratedScoped() 305 | { 306 | var source = @" 307 | using Microsoft.Extensions.DependencyInjection; 308 | class C 309 | { 310 | void M(IServiceCollection services) 311 | { 312 | services.Discover(); 313 | } 314 | } 315 | [Inject(ServiceLifetime.Scoped)] 316 | class MyService 317 | { 318 | }"; 319 | var (_, extensionCode) = GetGeneratedOutput(source); 320 | extensionCode.ShouldNotBeNull(); 321 | 322 | const string expectedExtensionCode = @"// 323 | using Microsoft.Extensions.DependencyInjection; 324 | 325 | public static class GeneratedServicesExtension 326 | { 327 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 328 | internal static void Discover(this IServiceCollection services) 329 | { 330 | services.AddScoped(); 331 | } 332 | } 333 | 334 | public static class FooDiscoverer 335 | { 336 | public static void Discover(IServiceCollection services) => services.Discover(); 337 | } 338 | "; 339 | extensionCode.ShouldBe(expectedExtensionCode); 340 | } 341 | 342 | [Fact] 343 | public void GeneratedScopedWithSpecificMethod() 344 | { 345 | var source = @" 346 | using Microsoft.Extensions.DependencyInjection; 347 | class C 348 | { 349 | void M(IServiceCollection services) 350 | { 351 | services.Discover(); 352 | } 353 | } 354 | [InjectScoped] 355 | class MyService 356 | { 357 | }"; 358 | var (_, extensionCode) = GetGeneratedOutput(source); 359 | extensionCode.ShouldNotBeNull(); 360 | 361 | const string expectedExtensionCode = @"// 362 | using Microsoft.Extensions.DependencyInjection; 363 | 364 | public static class GeneratedServicesExtension 365 | { 366 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 367 | internal static void Discover(this IServiceCollection services) 368 | { 369 | services.AddScoped(); 370 | } 371 | } 372 | 373 | public static class FooDiscoverer 374 | { 375 | public static void Discover(IServiceCollection services) => services.Discover(); 376 | } 377 | "; 378 | extensionCode.ShouldBe(expectedExtensionCode); 379 | } 380 | 381 | [Fact] 382 | public void GeneratedTransient() 383 | { 384 | var source = @" 385 | using Microsoft.Extensions.DependencyInjection; 386 | class C 387 | { 388 | void M(IServiceCollection services) 389 | { 390 | services.Discover(); 391 | } 392 | } 393 | [Inject(ServiceLifetime.Transient)] 394 | class MyService 395 | { 396 | }"; 397 | var (_, extensionCode) = GetGeneratedOutput(source); 398 | extensionCode.ShouldNotBeNull(); 399 | 400 | const string expectedExtensionCode = @"// 401 | using Microsoft.Extensions.DependencyInjection; 402 | 403 | public static class GeneratedServicesExtension 404 | { 405 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 406 | internal static void Discover(this IServiceCollection services) 407 | { 408 | services.AddTransient(); 409 | } 410 | } 411 | 412 | public static class FooDiscoverer 413 | { 414 | public static void Discover(IServiceCollection services) => services.Discover(); 415 | } 416 | "; 417 | extensionCode.ShouldBe(expectedExtensionCode); 418 | } 419 | 420 | [Fact] 421 | public void GeneratedTransientWithSpecificMethod() 422 | { 423 | var source = @" 424 | using Microsoft.Extensions.DependencyInjection; 425 | class C 426 | { 427 | void M(IServiceCollection services) 428 | { 429 | services.Discover(); 430 | } 431 | } 432 | [InjectTransient] 433 | class MyService 434 | { 435 | }"; 436 | var (_, extensionCode) = GetGeneratedOutput(source); 437 | extensionCode.ShouldNotBeNull(); 438 | 439 | const string expectedExtensionCode = @"// 440 | using Microsoft.Extensions.DependencyInjection; 441 | 442 | public static class GeneratedServicesExtension 443 | { 444 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 445 | internal static void Discover(this IServiceCollection services) 446 | { 447 | services.AddTransient(); 448 | } 449 | } 450 | 451 | public static class FooDiscoverer 452 | { 453 | public static void Discover(IServiceCollection services) => services.Discover(); 454 | } 455 | "; 456 | extensionCode.ShouldBe(expectedExtensionCode); 457 | } 458 | 459 | [Fact] 460 | public void GeneratedSingleton() 461 | { 462 | var source = @" 463 | using Microsoft.Extensions.DependencyInjection; 464 | class C 465 | { 466 | void M(IServiceCollection services) 467 | { 468 | services.Discover(); 469 | } 470 | } 471 | [Inject(ServiceLifetime.Singleton)] 472 | class MyService 473 | { 474 | }"; 475 | var (_, extensionCode) = GetGeneratedOutput(source); 476 | extensionCode.ShouldNotBeNull(); 477 | 478 | const string expectedExtensionCode = @"// 479 | using Microsoft.Extensions.DependencyInjection; 480 | 481 | public static class GeneratedServicesExtension 482 | { 483 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 484 | internal static void Discover(this IServiceCollection services) 485 | { 486 | services.AddSingleton(); 487 | } 488 | } 489 | 490 | public static class FooDiscoverer 491 | { 492 | public static void Discover(IServiceCollection services) => services.Discover(); 493 | } 494 | "; 495 | extensionCode.ShouldBe(expectedExtensionCode); 496 | } 497 | 498 | [Fact] 499 | public void GeneratedSingletonWithSpecificMethod() 500 | { 501 | var source = @" 502 | using Microsoft.Extensions.DependencyInjection; 503 | class C 504 | { 505 | void M(IServiceCollection services) 506 | { 507 | services.Discover(); 508 | } 509 | } 510 | [InjectSingleton] 511 | class MyService 512 | { 513 | }"; 514 | var (_, extensionCode) = GetGeneratedOutput(source); 515 | extensionCode.ShouldNotBeNull(); 516 | 517 | const string expectedExtensionCode = @"// 518 | using Microsoft.Extensions.DependencyInjection; 519 | 520 | public static class GeneratedServicesExtension 521 | { 522 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 523 | internal static void Discover(this IServiceCollection services) 524 | { 525 | services.AddSingleton(); 526 | } 527 | } 528 | 529 | public static class FooDiscoverer 530 | { 531 | public static void Discover(IServiceCollection services) => services.Discover(); 532 | } 533 | "; 534 | extensionCode.ShouldBe(expectedExtensionCode); 535 | } 536 | 537 | [Fact] 538 | public void GeneratedCodeForInterface() 539 | { 540 | var source = @" 541 | using Microsoft.Extensions.DependencyInjection; 542 | 543 | namespace WebApp 544 | { 545 | class C 546 | { 547 | void M(IServiceCollection services) 548 | { 549 | services.Discover(); 550 | } 551 | } 552 | [Inject] 553 | class MyService : IMyInterface 554 | { 555 | } 556 | interface IMyInterface 557 | { 558 | } 559 | }"; 560 | var (_, extensionCode) = GetGeneratedOutput(source); 561 | extensionCode.ShouldNotBeNull(); 562 | 563 | const string expectedExtensionCode = @"// 564 | using Microsoft.Extensions.DependencyInjection; 565 | using WebApp; 566 | 567 | namespace WebApp 568 | { 569 | public static class GeneratedServicesExtension 570 | { 571 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 572 | internal static void Discover(this IServiceCollection services) 573 | { 574 | services.AddTransient(); 575 | services.AddTransient(); 576 | } 577 | } 578 | } 579 | 580 | public static class FooDiscoverer 581 | { 582 | public static void Discover(IServiceCollection services) => services.Discover(); 583 | } 584 | "; 585 | extensionCode.ShouldBe(expectedExtensionCode); 586 | } 587 | 588 | [Fact] 589 | public void GeneratedCodeForBaseInterfaces() 590 | { 591 | var source = @" 592 | using Microsoft.Extensions.DependencyInjection; 593 | 594 | namespace WebApp 595 | { 596 | class C 597 | { 598 | void M(IServiceCollection services) 599 | { 600 | services.Discover(); 601 | } 602 | } 603 | [Inject] 604 | class MyService : MyBaseClass 605 | { 606 | } 607 | class MyBaseClass : IMyInterface1 608 | { 609 | } 610 | interface IMyInterface1 : IMyInterface2 611 | { 612 | } 613 | interface IMyInterface2 614 | { 615 | } 616 | }"; 617 | var (_, extensionCode) = GetGeneratedOutput(source); 618 | extensionCode.ShouldNotBeNull(); 619 | 620 | const string expectedExtensionCode = @"// 621 | using Microsoft.Extensions.DependencyInjection; 622 | using WebApp; 623 | 624 | namespace WebApp 625 | { 626 | public static class GeneratedServicesExtension 627 | { 628 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 629 | internal static void Discover(this IServiceCollection services) 630 | { 631 | services.AddTransient(); 632 | services.AddTransient(); 633 | services.AddTransient(); 634 | } 635 | } 636 | } 637 | 638 | public static class FooDiscoverer 639 | { 640 | public static void Discover(IServiceCollection services) => services.Discover(); 641 | } 642 | "; 643 | extensionCode.ShouldBe(expectedExtensionCode); 644 | } 645 | 646 | [Fact] 647 | public void GeneratedCodeForGenericInterfaces() 648 | { 649 | var source = @" 650 | interface IGeneric { } 651 | interface IGeneric : IGeneric { } 652 | [InjectTransient] 653 | class C : IGeneric { }"; 654 | var (_, extensionCode) = GetGeneratedOutput(source); 655 | extensionCode.ShouldNotBeNull(); 656 | 657 | const string expectedExtensionCode = @"// 658 | using Microsoft.Extensions.DependencyInjection; 659 | 660 | public static class GeneratedServicesExtension 661 | { 662 | public static void DiscoverInFoo(this IServiceCollection services) => services.Discover(); 663 | internal static void Discover(this IServiceCollection services) 664 | { 665 | services.AddTransient(); 666 | services.AddTransient, C>(); 667 | services.AddTransient(); 668 | } 669 | } 670 | 671 | public static class FooDiscoverer 672 | { 673 | public static void Discover(IServiceCollection services) => services.Discover(); 674 | } 675 | "; 676 | extensionCode.ShouldBe(expectedExtensionCode); 677 | } 678 | 679 | private (string, string) GetGeneratedOutput(string source, bool executable = false) 680 | { 681 | var outputCompilation = CreateCompilation(source, executable); 682 | var trees = outputCompilation.SyntaxTrees.Reverse().Take(2).Reverse().ToList(); 683 | foreach (var tree in trees) 684 | { 685 | output.WriteLine(Path.GetFileName(tree.FilePath) + ":"); 686 | output.WriteLine(tree.ToString()); 687 | } 688 | return (trees.First().ToString(), trees[1].ToString()); 689 | } 690 | 691 | private static Compilation CreateCompilation(string source, bool executable) 692 | { 693 | var syntaxTree = CSharpSyntaxTree.ParseText(source); 694 | 695 | var references = new List(); 696 | foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) 697 | if (!assembly.IsDynamic && !string.IsNullOrWhiteSpace(assembly.Location)) 698 | references.Add(MetadataReference.CreateFromFile(assembly.Location)); 699 | 700 | var compilation = CSharpCompilation.Create("Foo", 701 | new SyntaxTree[] { syntaxTree }, 702 | references, 703 | new CSharpCompilationOptions(executable ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary)); 704 | 705 | var generator = new Generator(); 706 | 707 | var driver = CSharpGeneratorDriver.Create(generator); 708 | driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generateDiagnostics); 709 | 710 | var compileDiagnostics = outputCompilation.GetDiagnostics(); 711 | compileDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error).ShouldBeFalse("Failed: " + compileDiagnostics.FirstOrDefault()?.GetMessage()); 712 | 713 | generateDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error).ShouldBeFalse("Failed: " + generateDiagnostics.FirstOrDefault()?.GetMessage()); 714 | return outputCompilation; 715 | } 716 | } 717 | -------------------------------------------------------------------------------- /test/SourceInjectTests/SourceInjectTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net6.0 4 | false 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | all 16 | 17 | 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | all 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | --------------------------------------------------------------------------------