From 89f8c98e66ebfe31542db527076a0b63eb0a3c84 Mon Sep 17 00:00:00 2001 From: Travis Illig Date: Thu, 21 Jul 2022 13:53:40 -0700 Subject: [PATCH 1/5] Update build to .NET 6 SDK, targeting net472. --- .editorconfig | 227 +++++++- .vscode/launch.json | 23 - .vscode/settings.json | 11 + .vscode/tasks.json | 2 +- NuGet.Config | 4 +- appveyor.yml | 30 +- build.ps1 | 79 +-- build/Analyzers.ruleset | 25 +- build/Autofac.Build.psd1 | 2 +- build/Autofac.Build.psm1 | 506 +++++++++--------- build/CodeAnalysisDictionary.xml | 47 -- build/Test.ruleset | 64 +++ build/stylecop.json | 14 + global.json | 12 +- .../Autofac.Integration.Web.csproj | 67 +-- .../Autofac.Integration.Web.Test.csproj | 24 +- 16 files changed, 682 insertions(+), 455 deletions(-) delete mode 100644 .vscode/launch.json delete mode 100644 build/CodeAnalysisDictionary.xml create mode 100644 build/Test.ruleset create mode 100644 build/stylecop.json diff --git a/.editorconfig b/.editorconfig index 1d82f31..9f1a417 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,28 +1,199 @@ -; EditorConfig to support per-solution formatting. -; Use the EditorConfig VS add-in to make this work. -; http://editorconfig.org/ - -; This is the default for the codeline. -root = true - -[*] -end_of_line = CRLF - -[*.{config,cs,xml}] -indent_style = space -indent_size = 4 -trim_trailing_whitespace = true - -[*.{proj,props,sln,targets}] -indent_style = tab -trim_trailing_whitespace = true - -[*.{kproj,csproj,json,ps1,psd1,psm1,resx,rst}] -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -[NuGet.Config] -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true +; EditorConfig to support per-solution formatting. +; Use the EditorConfig VS add-in to make this work. +; http://editorconfig.org/ + +; This is the default for the codeline. +root = true + +[*] +indent_style = space +trim_trailing_whitespace = true +insert_final_newline = true + +; .NET Code - almost, but not exactly, the same suggestions as corefx +; https://github.com/dotnet/corefx/blob/master/.editorconfig +[*.cs] +indent_size = 4 +charset = utf-8-bom + +; New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +; Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = one_less_than_current + +; Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion + +; Avoid this. unless absolutely necessary +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion + +; Types: use keywords instead of BCL types, using var is fine. +csharp_style_var_when_type_is_apparent = false:none +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +; Name all constant fields using PascalCase +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = warning +dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.required_modifiers = const +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +; Static fields should be _camelCase +dotnet_naming_rule.static_fields_should_be_camel_case.severity = warning +dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields +dotnet_naming_rule.static_fields_should_be_camel_case.style = camel_case_underscore_style +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static +dotnet_naming_symbols.static_fields.applicable_accessibilities = private, internal, private_protected + +; Static readonly fields should be PascalCase +dotnet_naming_rule.static_readonly_fields_should_be_pascal_case.severity = warning +dotnet_naming_rule.static_readonly_fields_should_be_pascal_case.symbols = static_readonly_fields +dotnet_naming_rule.static_readonly_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_symbols.static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.static_readonly_fields.required_modifiers = static, readonly +dotnet_naming_symbols.static_readonly_fields.applicable_accessibilities = private, internal, private_protected + +; Internal and private fields should be _camelCase +dotnet_naming_rule.camel_case_for_private_internal_fields.severity = warning +dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields +dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style +dotnet_naming_symbols.private_internal_fields.applicable_kinds = field +dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal +dotnet_naming_style.camel_case_underscore_style.required_prefix = _ +dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case + +; Code style defaults +csharp_using_directive_placement = outside_namespace:suggestion +dotnet_sort_system_directives_first = true +csharp_prefer_braces = true:refactoring +csharp_preserve_single_line_blocks = true:none +csharp_preserve_single_line_statements = false:none +csharp_prefer_static_local_function = true:suggestion +csharp_prefer_simple_using_statement = false:none +csharp_style_prefer_switch_expression = true:suggestion + +; Code quality +dotnet_style_readonly_field = true:suggestion +dotnet_code_quality_unused_parameters = non_public:suggestion + +; Expression-level preferences +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:refactoring +dotnet_style_prefer_conditional_expression_over_return = true:refactoring +csharp_prefer_simple_default_expression = true:suggestion + +# Expression-bodied members +csharp_style_expression_bodied_methods = true:refactoring +csharp_style_expression_bodied_constructors = true:refactoring +csharp_style_expression_bodied_operators = true:refactoring +csharp_style_expression_bodied_properties = true:refactoring +csharp_style_expression_bodied_indexers = true:refactoring +csharp_style_expression_bodied_accessors = true:refactoring +csharp_style_expression_bodied_lambdas = true:refactoring +csharp_style_expression_bodied_local_functions = true:refactoring + +# Pattern matching +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion + +# Null checking preferences +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion + +# Other features +csharp_style_namespace_declarations = file_scoped:suggestion +csharp_style_prefer_index_operator = false:none +csharp_style_prefer_range_operator = false:none +csharp_style_pattern_local_over_anonymous_function = false:none + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = do_not_ignore +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +; .NET project files and MSBuild - match defaults for VS +[*.{csproj,nuspec,proj,projitems,props,shproj,targets,vbproj,vcxproj,vcxproj.filters,vsixmanifest,vsct}] +indent_size = 2 + +; .NET solution files - match defaults for VS +[*.sln] +indent_style = tab + +; Config - match XML and default nuget.config template +[*.config] +indent_size = 2 + +; Resources - match defaults for VS +[*.resx] +indent_size = 2 + +; Static analysis rulesets - match defaults for VS +[*.ruleset] +indent_size = 2 + +; HTML, XML - match defaults for VS +[*.{cshtml,html,xml}] +indent_size = 4 + +; JavaScript and JS mixes - match eslint settings; JSON also matches .NET Core templates +[*.{js,json,ts,vue}] +indent_size = 2 + +; Markdown - match markdownlint settings +[*.{md,markdown}] +indent_size = 2 + +; PowerShell - match defaults for New-ModuleManifest and PSScriptAnalyzer Invoke-Formatter +[*.{ps1,psd1,psm1}] +indent_size = 4 +charset = utf-8-bom + +; ReStructuredText - standard indentation format from examples +[*.rst] +indent_size = 2 diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 924241d..0000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "configurations": [ - { - "args": [ - ], - "console": "internalConsole", - "cwd": "${workspaceFolder}/test/Autofac.Configuration.Test", - "name": ".NET Core Launch (console)", - "preLaunchTask": "build", - "program": "${workspaceFolder}/test/Autofac.Integration.Web.Test/bin/Debug/net461/Autofac.Integration.Web.Test.dll", - "request": "launch", - "stopAtEntry": false, - "type": "coreclr" - }, - { - "name": ".NET Core Attach", - "processId": "${command:pickProcess}", - "request": "attach", - "type": "coreclr" - } - ], - "version": "0.2.0" -} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 804f965..3453b56 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,15 @@ { + "cSpell.words": [ + "autofac", + "cref", + "inheritdoc", + "langword", + "paramref", + "seealso", + "typeparam", + "unmanaged", + "xunit" + ], "dotnet-test-explorer.runInParallel": true, "dotnet-test-explorer.testProjectPath": "test/**/*.Test.csproj" } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index e5112e9..557ce61 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -3,7 +3,7 @@ { "args": [ "build", - "${workspaceFolder}/Autofac.Configuration.sln", + "${workspaceFolder}/Autofac.Web.sln", "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], diff --git a/NuGet.Config b/NuGet.Config index bb8de19..9d853bd 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -1,9 +1,9 @@  - + - + diff --git a/appveyor.yml b/appveyor.yml index 9088f17..787e958 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,14 +1,14 @@ -version: 6.0.0.{build} +image: Visual Studio 2022 + +version: 6.1.0.{build} dotnet_csproj: - version_prefix: '6.0.0' + version_prefix: '6.1.0' patch: true file: 'src\**\*.csproj' configuration: Release -image: Visual Studio 2019 - environment: DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true NUGET_XMLDOC_MODE: skip @@ -20,20 +20,20 @@ nuget: clone_depth: 1 -test: off +test: false build_script: -- ps: .\build.ps1 + - pwsh: .\build.ps1 artifacts: -- path: artifacts\packages\**\*.nupkg - name: MyGet + - path: artifacts\packages\**\*.*nupkg + name: MyGet + type: NuGetPackage deploy: -- provider: NuGet - server: https://www.myget.org/F/autofac/api/v2/package - api_key: - secure: xUXExgVAagrdEicCjSxsQVrwiLo2TtnfqMbYB9Cauq2cpbm/EVz957PBK0v/GEYq - skip_symbols: true - symbol_server: https://www.myget.org/F/autofac/symbols/api/v2/package - artifact: MyGet + - provider: NuGet + server: https://www.myget.org/F/autofac/api/v2/package + symbol_server: https://www.myget.org/F/autofac/api/v2/package + api_key: + secure: xUXExgVAagrdEicCjSxsQVrwiLo2TtnfqMbYB9Cauq2cpbm/EVz957PBK0v/GEYq + artifact: MyGet diff --git a/build.ps1 b/build.ps1 index 1d154bd..1bf2d7e 100644 --- a/build.ps1 +++ b/build.ps1 @@ -3,44 +3,61 @@ ######################## Push-Location $PSScriptRoot -Import-Module $PSScriptRoot\Build\Autofac.Build.psd1 -Force +try { + Import-Module $PSScriptRoot/build/Autofac.Build.psd1 -Force -$artifactsPath = "$PSScriptRoot\artifacts" -$packagesPath = "$artifactsPath\packages" -$sdkVersion = (Get-Content "$PSScriptRoot\global.json" | ConvertFrom-Json).sdk.version + $artifactsPath = "$PSScriptRoot/artifacts" + $packagesPath = "$artifactsPath/packages" -# Clean up artifacts folder -if (Test-Path $artifactsPath) { - Write-Message "Cleaning $artifactsPath folder" - Remove-Item $artifactsPath -Force -Recurse -} + $globalJson = (Get-Content "$PSScriptRoot/global.json" | ConvertFrom-Json -NoEnumerate); + + $sdkVersion = $globalJson.sdk.version + + # Clean up artifacts folder + if (Test-Path $artifactsPath) { + Write-Message "Cleaning $artifactsPath folder" + Remove-Item $artifactsPath -Force -Recurse + } -# Install dotnet CLI -Write-Message "Installing .NET Core SDK version $sdkVersion" -Install-DotNetCli -Version $sdkVersion + # Install dotnet SDK versions during CI. In a local build we assume you have + # everything installed; on CI we'll force the install. If you install _any_ + # SDKs, you have to install _all_ of them because you can't install SDKs in + # two different locations. dotnet CLI locates SDKs relative to the + # executable. + if ($Null -ne $env:APPVEYOR_BUILD_NUMBER) { + Install-DotNetCli -Version $sdkVersion + foreach ($additional in $globalJson.additionalSdks) + { + Install-DotNetCli -Version $additional; + } + } -# Write out dotnet information -& dotnet --info + # Write out dotnet information + & dotnet --info -# Set version suffix -$branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL]; -$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL]; -$versionSuffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "master" -and $revision -ne "local"] + # Set version suffix + $branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$NULL -ne $env:APPVEYOR_REPO_BRANCH]; + $revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$NULL -ne $env:APPVEYOR_BUILD_NUMBER]; + $versionSuffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)).Replace('/', '-'))-$revision" }[$branch -eq "master" -and $revision -ne "local"] -Write-Message "Package version suffix is '$versionSuffix'" + Write-Message "Package version suffix is '$versionSuffix'" -# Package restore -Write-Message "Restoring packages" -Get-DotNetProjectDirectory -RootPath $PSScriptRoot | Restore-DependencyPackages + # Package restore + Write-Message "Restoring packages" + Get-DotNetProjectDirectory -RootPath $PSScriptRoot | Restore-DependencyPackages -# Build/package -Write-Message "Building projects and packages" -Get-DotNetProjectDirectory -RootPath $PSScriptRoot\src | Invoke-DotNetPack -PackagesPath $packagesPath -VersionSuffix $versionSuffix + # Build/package + Write-Message "Building projects and packages" + Get-DotNetProjectDirectory -RootPath $PSScriptRoot\src | Invoke-DotNetPack -PackagesPath $packagesPath -VersionSuffix $versionSuffix -# Test -Write-Message "Executing unit tests" -Get-DotNetProjectDirectory -RootPath $PSScriptRoot\test | Invoke-Test + # Test + Write-Message "Executing unit tests" + Get-DotNetProjectDirectory -RootPath $PSScriptRoot\test | Invoke-Test -# Finished -Write-Message "Build finished" -Pop-Location + + # Finished + Write-Message "Build finished" +} +finally { + Pop-Location +} diff --git a/build/Analyzers.ruleset b/build/Analyzers.ruleset index 8e76993..4d4e23d 100644 --- a/build/Analyzers.ruleset +++ b/build/Analyzers.ruleset @@ -1,7 +1,16 @@  - - + + + + + + + + + + + @@ -25,13 +34,7 @@ - - - - - - - + @@ -41,9 +44,7 @@ - - - \ No newline at end of file + diff --git a/build/Autofac.Build.psd1 b/build/Autofac.Build.psd1 index e8b04e3..8a5bfac 100644 --- a/build/Autofac.Build.psd1 +++ b/build/Autofac.Build.psd1 @@ -1,6 +1,6 @@ @{ RootModule = '.\Autofac.Build.psm1' - ModuleVersion = '0.2.0' + ModuleVersion = '0.3.0' GUID = '55d3f738-f48f-4497-9b2c-ecd90ec1f978' Author = 'Autofac Contributors' CompanyName = 'Autofac' diff --git a/build/Autofac.Build.psm1 b/build/Autofac.Build.psm1 index a0144c0..c19666f 100644 --- a/build/Autofac.Build.psm1 +++ b/build/Autofac.Build.psm1 @@ -1,250 +1,256 @@ -# EXIT CODES -# 1: dotnet packaging failure -# 2: dotnet publishing failure -# 3: Unit test failure -# 4: dotnet / NuGet package restore failure - -<# - .SYNOPSIS - Writes a build progress message to the host. - - .PARAMETER Message - The message to write. -#> -function Write-Message -{ - [CmdletBinding()] - Param( - [Parameter(Mandatory=$True, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False)] - [ValidateNotNullOrEmpty()] - [string] - $Message - ) - - Write-Host "[BUILD] $Message" -ForegroundColor Cyan -} - -<# - .SYNOPSIS - Gets the set of directories in which projects are available for compile/processing. - - .PARAMETER RootPath - Path where searching for project directories should begin. -#> -function Get-DotNetProjectDirectory -{ - [CmdletBinding()] - Param( - [Parameter(Mandatory=$True, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False)] - [ValidateNotNullOrEmpty()] - [string] - $RootPath - ) - - Get-ChildItem -Path $RootPath -Recurse -Include "*.csproj" | Select-Object @{ Name="ParentFolder"; Expression={ $_.Directory.FullName.TrimEnd("\") } } | Select-Object -ExpandProperty ParentFolder -} - -<# - .SYNOPSIS - Runs the dotnet CLI install script from GitHub to install a project-local - copy of the CLI. -#> -function Install-DotNetCli -{ - [CmdletBinding()] - Param( - [string] - $Version = "Latest" - ) - - if ($null -ne (Get-Command "dotnet" -ErrorAction SilentlyContinue)) - { - $installedVersion = dotnet --version - if ($installedVersion -eq $Version) - { - Write-Message ".NET Core SDK version $Version is already installed" - return; - } - } - - $callerPath = Split-Path $MyInvocation.PSCommandPath - $installDir = Join-Path -Path $callerPath -ChildPath ".dotnet\cli" - if (!(Test-Path $installDir)) - { - New-Item -ItemType Directory -Path "$installDir" | Out-Null - } - - # Download the dotnet CLI install script - if (!(Test-Path .\dotnet\install.ps1)) - { - Invoke-WebRequest "https://dot.net/v1/dotnet-install.ps1" -OutFile ".\.dotnet\dotnet-install.ps1" - } - - # Run the dotnet CLI install - & .\.dotnet\dotnet-install.ps1 -InstallDir "$installDir" -Version $Version - - # Add the dotnet folder path to the process. - $env:PATH = "$installDir;$env:PATH" -} - -<# -.SYNOPSIS - Builds a project using dotnet cli. -.DESCRIPTION - Builds a project in a specified directory using the dotnet cli. -.PARAMETER DirectoryName - The path to the directory containing the project to build. -#> -function Invoke-DotNetBuild -{ - [CmdletBinding()] - Param( - [Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)] - [ValidateNotNull()] - [System.IO.DirectoryInfo[]] - $ProjectDirectory - ) - Process - { - foreach($Project in $ProjectDirectory) - { - & dotnet build ("""" + $Project.FullName + """") --configuration Release - if ($LASTEXITCODE -ne 0) - { - exit 1 - } - } - } -} - -<# - .SYNOPSIS - Invokes the dotnet utility to package a project. - - .PARAMETER ProjectDirectory - Path to the directory containing the project to package. - - .PARAMETER PackagesPath - Path to the "artifacts\packages" folder where packages should go. - - .PARAMETER VersionSuffix - The version suffix to use for the NuGet package version. -#> -function Invoke-DotNetPack -{ - [CmdletBinding()] - Param( - [Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)] - [ValidateNotNull()] - [System.IO.DirectoryInfo[]] - $ProjectDirectory, - - [Parameter(Mandatory=$True, ValueFromPipeline=$False)] - [ValidateNotNull()] - [System.IO.DirectoryInfo] - $PackagesPath, - - [Parameter(Mandatory=$True, ValueFromPipeline=$False)] - [AllowEmptyString()] - [string] - $VersionSuffix - ) - Begin - { - New-Item -Path $PackagesPath -ItemType Directory -Force | Out-Null - } - Process - { - foreach($Project in $ProjectDirectory) - { - if ($VersionSuffix -eq "") - { - & dotnet build ("""" + $Project.FullName + """") --configuration Release - } - else - { - & dotnet build ("""" + $Project.FullName + """") --configuration Release --version-suffix $VersionSuffix - } - if ($LASTEXITCODE -ne 0) - { - exit 1 - } - - if ($VersionSuffix -eq "") - { - & dotnet pack ("""" + $Project.FullName + """") --configuration Release --output $PackagesPath - } - else - { - & dotnet pack ("""" + $Project.FullName + """") --configuration Release --version-suffix $VersionSuffix --output $PackagesPath - } - if ($LASTEXITCODE -ne 0) - { - exit 1 - } - } - } -} - -<# - .Synopsis - Invokes dotnet test command. - - .Parameter ProjectDirectory - Path to the directory containing the project to package. -#> -function Invoke-Test -{ - [CmdletBinding()] - Param( - [Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)] - [ValidateNotNull()] - [System.IO.DirectoryInfo[]] - $ProjectDirectory - ) - Process - { - foreach($Project in $ProjectDirectory) - { - Push-Location $Project - - & dotnet test --configuration Release --logger:trx - if ($LASTEXITCODE -ne 0) - { - Pop-Location - exit 3 - } - - Pop-Location - } - } -} - -<# - .SYNOPSIS - Restores dependencies using the dotnet utility. - - .PARAMETER ProjectDirectory - Path to the directory containing the project with dependencies to restore. -#> -function Restore-DependencyPackages -{ - [CmdletBinding()] - Param( - [Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)] - [ValidateNotNull()] - [System.IO.DirectoryInfo[]] - $ProjectDirectory - ) - Process - { - foreach($Project in $ProjectDirectory) - { - & dotnet restore ("""" + $Project.FullName + """") --no-cache - if($LASTEXITCODE -ne 0) - { - exit 4 - } - } - } -} +# EXIT CODES +# 1: dotnet packaging failure +# 2: dotnet publishing failure +# 3: Unit test failure +# 4: dotnet / NuGet package restore failure + +<# +.SYNOPSIS + Gets the set of directories in which projects are available for compile/processing. + +.PARAMETER RootPath + Path where searching for project directories should begin. +#> +function Get-DotNetProjectDirectory { + [CmdletBinding()] + Param( + [Parameter(Mandatory = $True, ValueFromPipeline = $False, ValueFromPipelineByPropertyName = $False)] + [ValidateNotNullOrEmpty()] + [string] + $RootPath + ) + + Get-ChildItem -Path $RootPath -Recurse -Include "*.csproj" | Select-Object @{ Name = "ParentFolder"; Expression = { $_.Directory.FullName.TrimEnd("\") } } | Select-Object -ExpandProperty ParentFolder +} + +<# +.SYNOPSIS + Runs the dotnet CLI install script from GitHub to install a project-local + copy of the CLI. +#> +function Install-DotNetCli { + [CmdletBinding()] + Param( + [string] + $Version = "Latest" + ) + Write-Message "Installing .NET SDK version $Version" + + $callerPath = Split-Path $MyInvocation.PSCommandPath + $installDir = Join-Path -Path $callerPath -ChildPath ".dotnet/cli" + if (!(Test-Path $installDir)) { + New-Item -ItemType Directory -Path "$installDir" | Out-Null + } + + # Download the dotnet CLI install script + if ($IsWindows) { + if (!(Test-Path ./.dotnet/dotnet-install.ps1)) { + Invoke-WebRequest "https://dot.net/v1/dotnet-install.ps1" -OutFile "./.dotnet/dotnet-install.ps1" + } + + & ./.dotnet/dotnet-install.ps1 -InstallDir "$installDir" -Version $Version + } else { + if (!(Test-Path ./.dotnet/dotnet-install.sh)) { + Invoke-WebRequest "https://dot.net/v1/dotnet-install.sh" -OutFile "./.dotnet/dotnet-install.sh" + } + + & bash ./.dotnet/dotnet-install.sh --install-dir "$installDir" --version $Version + } + + Add-Path "$installDir" +} + +<# +.SYNOPSIS + Appends a given value to the path but only if the value does not yet exist within the path. +.PARAMETER Path + The path to append. +#> +function Add-Path { + [CmdletBinding()] + Param( + [ValidateNotNullOrEmpty()] + [string] + $Path + ) + + $pathSeparator = ":"; + + if ($IsWindows) { + $pathSeparator = ";"; + } + + $pathValues = $env:PATH.Split($pathSeparator); + if ($pathValues -Contains $Path) { + return; + } + + $env:PATH = "${Path}${pathSeparator}$env:PATH" +} + +<# +.SYNOPSIS + Builds a project using dotnet cli. +.DESCRIPTION + Builds a project in a specified directory using the dotnet cli. +.PARAMETER DirectoryName + The path to the directory containing the project to build. +#> +function Invoke-DotNetBuild { + [CmdletBinding()] + Param( + [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] + [ValidateNotNull()] + [System.IO.DirectoryInfo[]] + $ProjectDirectory + ) + Process { + foreach ($Project in $ProjectDirectory) { + & dotnet build ("""" + $Project.FullName + """") --configuration Release + if ($LASTEXITCODE -ne 0) { + exit 1 + } + } + } +} + +<# +.SYNOPSIS + Invokes the dotnet utility to package a project. + +.PARAMETER ProjectDirectory + Path to the directory containing the project to package. + +.PARAMETER PackagesPath + Path to the "artifacts/packages" folder where packages should go. + +.PARAMETER VersionSuffix + The version suffix to use for the NuGet package version. +#> +function Invoke-DotNetPack { + [CmdletBinding()] + Param( + [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] + [ValidateNotNull()] + [System.IO.DirectoryInfo[]] + $ProjectDirectory, + + [Parameter(Mandatory = $True, ValueFromPipeline = $False)] + [ValidateNotNull()] + [System.IO.DirectoryInfo] + $PackagesPath, + + [Parameter(Mandatory = $True, ValueFromPipeline = $False)] + [AllowEmptyString()] + [string] + $VersionSuffix + ) + Begin { + New-Item -Path $PackagesPath -ItemType Directory -Force | Out-Null + } + Process { + foreach ($Project in $ProjectDirectory) { + if ($VersionSuffix -eq "") { + & dotnet build ("""" + $Project.FullName + """") --configuration Release + } + else { + & dotnet build ("""" + $Project.FullName + """") --configuration Release --version-suffix $VersionSuffix + } + if ($LASTEXITCODE -ne 0) { + exit 1 + } + + if ($VersionSuffix -eq "") { + & dotnet pack ("""" + $Project.FullName + """") --configuration Release --output $PackagesPath + } + else { + & dotnet pack ("""" + $Project.FullName + """") --configuration Release --version-suffix $VersionSuffix --output $PackagesPath + } + if ($LASTEXITCODE -ne 0) { + exit 1 + } + } + } +} + +<# +.SYNOPSIS + Invokes dotnet test command. + +.PARAMETER ProjectDirectory + Path to the directory containing the project to package. +#> +function Invoke-Test { + [CmdletBinding()] + Param( + [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] + [ValidateNotNull()] + [System.IO.DirectoryInfo[]] + $ProjectDirectory + ) + Process { + foreach ($Project in $ProjectDirectory) { + Push-Location $Project + + & dotnet test ` + --configuration Release ` + --logger:trx ` + /p:CollectCoverage=true ` + /p:CoverletOutput="../../artifacts/coverage/$($Project.Name)/" ` + /p:CoverletOutputFormat="json%2clcov" ` + /p:ExcludeByAttribute=CompilerGeneratedAttribute ` + /p:ExcludeByAttribute=GeneratedCodeAttribute + + if ($LASTEXITCODE -ne 0) { + Pop-Location + exit 3 + } + + Pop-Location + } + } +} + +<# +.SYNOPSIS + Restores dependencies using the dotnet utility. + +.PARAMETER ProjectDirectory + Path to the directory containing the project with dependencies to restore. +#> +function Restore-DependencyPackages { + [CmdletBinding()] + Param( + [Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] + [ValidateNotNull()] + [System.IO.DirectoryInfo[]] + $ProjectDirectory + ) + Process { + foreach ($Project in $ProjectDirectory) { + & dotnet restore ("""" + $Project.FullName + """") --no-cache + if ($LASTEXITCODE -ne 0) { + exit 4 + } + } + } +} + +<# +.SYNOPSIS + Writes a build progress message to the host. + +.PARAMETER Message + The message to write. +#> +function Write-Message { + [CmdletBinding()] + Param( + [Parameter(Mandatory = $True, ValueFromPipeline = $False, ValueFromPipelineByPropertyName = $False)] + [ValidateNotNullOrEmpty()] + [string] + $Message + ) + + Write-Host "[BUILD] $Message" -ForegroundColor Cyan +} diff --git a/build/CodeAnalysisDictionary.xml b/build/CodeAnalysisDictionary.xml deleted file mode 100644 index 0f1b469..0000000 --- a/build/CodeAnalysisDictionary.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - Api - Autofac - autowired - autowiring - composable - configurator - Ioc - Mef - Moq - multitenancy - Mvc - Mvx - Mvvm - startable - Owin - - - - - diff --git a/build/Test.ruleset b/build/Test.ruleset new file mode 100644 index 0000000..0cac6ad --- /dev/null +++ b/build/Test.ruleset @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/stylecop.json b/build/stylecop.json new file mode 100644 index 0000000..8f5c703 --- /dev/null +++ b/build/stylecop.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": { + "documentationRules": { + "companyName": "Autofac Project", + "copyrightText": "Copyright (c) {companyName}. All rights reserved.\nLicensed under the {licenseName} License. See {licenseFile} in the project root for license information.", + "variables": { + "licenseFile": "LICENSE", + "licenseName": "MIT" + }, + "xmlHeader": false + } + } +} diff --git a/global.json b/global.json index c630f74..d6fab23 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ -{ - "sdk": { - "version": "3.1.100", - "rollForward": "latestFeature" - } -} +{ + "sdk": { + "rollForward": "latestFeature", + "version": "6.0.301" + } +} diff --git a/src/Autofac.Integration.Web/Autofac.Integration.Web.csproj b/src/Autofac.Integration.Web/Autofac.Integration.Web.csproj index fa3a5f0..d2ce45b 100644 --- a/src/Autofac.Integration.Web/Autofac.Integration.Web.csproj +++ b/src/Autofac.Integration.Web/Autofac.Integration.Web.csproj @@ -1,53 +1,51 @@  - - ASP.NET web forms integration for Autofac. 0.0.1 - net472 - true - true + Autofac.Integration.Web + Autofac.Integration.Web + ASP.NET web forms integration for Autofac. + Copyright © 2014 Autofac Contributors + Autofac Contributors + Autofac + Autofac ../../Autofac.snk true - true + en-US + + net472 + latest + enable + true + true + ../../build/Analyzers.ruleset + AllEnabledByDefault + enable + Autofac.Web autofac;di;ioc;dependencyinjection Release notes are at https://github.com/autofac/Autofac.Web/releases icon.png https://autofac.org MIT + README.md git https://github.com/autofac/Autofac.Web - ../../build/Analyzers.ruleset + true true true - $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb - IOperation - Autofac Contributors - Autofac - Autofac - Copyright © 2014 Autofac Contributors - en-US + true + snupkg - - - - - - - All - - - All - - - + + + All - + All @@ -55,9 +53,6 @@ - - CodeAnalysisDictionary.xml - True True @@ -69,6 +64,16 @@ DependencyInjectionModuleResources.resx + + + + + + + + + + ResXFileCodeGenerator diff --git a/test/Autofac.Integration.Web.Test/Autofac.Integration.Web.Test.csproj b/test/Autofac.Integration.Web.Test/Autofac.Integration.Web.Test.csproj index dff2d2b..d17f5de 100644 --- a/test/Autofac.Integration.Web.Test/Autofac.Integration.Web.Test.csproj +++ b/test/Autofac.Integration.Web.Test/Autofac.Integration.Web.Test.csproj @@ -2,23 +2,31 @@ net472 - $(NoWarn);CS1591;SA1602;SA1611 + $(NoWarn);CS1591 true - Autofac.Integration.Web.Test ../../Autofac.snk true - ../../build/Analyzers.ruleset + true + ../../build/Test.ruleset false + latest + enable - - - - All + + + + + + + all - + + all + runtime; build; native; contentfiles; analyzers + From 1b99d9d6baa38e16e190ec9392867233d868d440 Mon Sep 17 00:00:00 2001 From: Travis Illig Date: Thu, 21 Jul 2022 14:09:54 -0700 Subject: [PATCH 2/5] Resolve new .NET 6 analyzer issues. --- .../Autofac.Integration.Web.csproj | 2 +- .../ContainerDisposalModule.cs | 37 ++++-------- .../ContainerProvider.cs | 33 +++-------- .../ContainerProviderContainer.cs | 35 +++-------- .../Forms/AttributedInjection.cs | 58 ++++++------------- .../Forms/AttributedInjectionModule.cs | 32 ++-------- .../Forms/DependencyInjectionAttribute.cs | 26 +-------- .../Forms/DependencyInjectionModule.cs | 41 +++++-------- .../Forms/IInjectionBehavior.cs | 26 +-------- .../Forms/InjectPropertiesAttribute.cs | 26 +-------- .../Forms/InjectUnsetPropertiesAttribute.cs | 26 +-------- .../Forms/NoInjection.cs | 26 +-------- .../Forms/PageInjectionBehavior.cs | 45 +++++++------- .../Forms/PropertyInjection.cs | 28 ++------- .../Forms/PropertyInjectionModule.cs | 32 ++-------- .../Forms/UnsetPropertyInjection.cs | 28 ++------- .../Forms/UnsetPropertyInjectionModule.cs | 32 ++-------- .../IContainerProvider.cs | 25 +------- .../IContainerProviderAccessor.cs | 25 +------- .../Properties/AssemblyInfo.cs | 5 +- .../RegistrationExtensions.cs | 31 ++-------- src/Autofac.Integration.Web/WebLifetime.cs | 25 +------- .../Autofac.Integration.Web.Test.csproj | 9 ++- .../Forms/AttributedInjectionModuleFixture.cs | 7 ++- .../RegistrationExtensionsFixture.cs | 5 +- 25 files changed, 148 insertions(+), 517 deletions(-) diff --git a/src/Autofac.Integration.Web/Autofac.Integration.Web.csproj b/src/Autofac.Integration.Web/Autofac.Integration.Web.csproj index d2ce45b..33a01cc 100644 --- a/src/Autofac.Integration.Web/Autofac.Integration.Web.csproj +++ b/src/Autofac.Integration.Web/Autofac.Integration.Web.csproj @@ -86,4 +86,4 @@ Designer - \ No newline at end of file + diff --git a/src/Autofac.Integration.Web/ContainerDisposalModule.cs b/src/Autofac.Integration.Web/ContainerDisposalModule.cs index d7263dd..147fa98 100644 --- a/src/Autofac.Integration.Web/ContainerDisposalModule.cs +++ b/src/Autofac.Integration.Web/ContainerDisposalModule.cs @@ -1,28 +1,8 @@ -// Contributed by Nicholas Blumhardt 2008-01-28 -// Copyright © 2011 Autofac Contributors -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; +using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using System.Web; @@ -34,7 +14,7 @@ namespace Autofac.Integration.Web /// public class ContainerDisposalModule : IHttpModule { - private IContainerProviderAccessor _containerProviderAccessor; + private IContainerProviderAccessor? _containerProviderAccessor; /// /// Disposes of the resources (other than memory) used by the module that implements . @@ -50,11 +30,15 @@ public void Dispose() public void Init(HttpApplication context) { if (context == null) + { throw new ArgumentNullException(nameof(context)); + } _containerProviderAccessor = context as IContainerProviderAccessor; if (_containerProviderAccessor == null) + { throw new InvalidOperationException(ContainerDisposalModuleResources.ApplicationMustImplementAccessor); + } var wrapper = new EventHandlerTaskAsyncHelper(OnEndRequest); @@ -64,11 +48,14 @@ public void Init(HttpApplication context) /// /// Dispose of the per-request container. /// + [SuppressMessage("CA1849", "CA1849", Justification = "If the value task is already completed, getting the result synchronously isn't a problem.")] private Task OnEndRequest(object sender, EventArgs e) { - var cp = _containerProviderAccessor.ContainerProvider; + var cp = _containerProviderAccessor?.ContainerProvider; if (cp == null) + { throw new InvalidOperationException(ContainerDisposalModuleResources.ContainerProviderNull); + } var valueTask = cp.EndRequestLifetime(); diff --git a/src/Autofac.Integration.Web/ContainerProvider.cs b/src/Autofac.Integration.Web/ContainerProvider.cs index 5fb5497..f6ae405 100644 --- a/src/Autofac.Integration.Web/ContainerProvider.cs +++ b/src/Autofac.Integration.Web/ContainerProvider.cs @@ -1,26 +1,5 @@ -// Contributed by Nicholas Blumhardt 2008-01-28 -// Copyright © 2011 Autofac Contributors -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Threading.Tasks; @@ -34,7 +13,7 @@ namespace Autofac.Integration.Web /// public class ContainerProvider : IContainerProvider { - private readonly Action _requestLifetimeConfiguration; + private readonly Action? _requestLifetimeConfiguration; /// /// Initializes a new instance of the class. @@ -49,9 +28,11 @@ public ContainerProvider(IContainer applicationContainer) /// Initializes a new instance of the class. /// /// The application container. - /// An action that will be executed when building + /// + /// An action that will be executed when building /// the per-request lifetime. The components visible within the request can be - /// customised here. + /// customized here. + /// public ContainerProvider(IContainer applicationContainer, Action requestLifetimeConfiguration) : this(applicationContainer) { diff --git a/src/Autofac.Integration.Web/ContainerProviderContainer.cs b/src/Autofac.Integration.Web/ContainerProviderContainer.cs index fed731b..893e2e5 100644 --- a/src/Autofac.Integration.Web/ContainerProviderContainer.cs +++ b/src/Autofac.Integration.Web/ContainerProviderContainer.cs @@ -1,26 +1,5 @@ -// Contributed by Chad Lee 2009-06-15 -// Copyright © 2011 Autofac Contributors -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; @@ -100,7 +79,7 @@ public ILifetimeScope BeginLifetimeScope(object tag) /// as the root scope. /// /// Action on a - /// that adds component registations visible only in the new scope. + /// that adds component registrations visible only in the new scope. /// A new lifetime scope. public ILifetimeScope BeginLifetimeScope(Action configurationAction) { @@ -119,7 +98,7 @@ public ILifetimeScope BeginLifetimeScope(Action configurationA /// /// The tag applied to the . /// Action on a - /// that adds component registations visible only in the new scope. + /// that adds component registrations visible only in the new scope. /// A new lifetime scope. public ILifetimeScope BeginLifetimeScope(object tag, Action configurationAction) { @@ -195,10 +174,9 @@ public object ResolveComponent(ResolveRequest request) /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// - [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "Disposing of this wrapper container should not result in the whole application container being disposed.")] - [SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Disposing of this wrapper container should not result in the whole application container being disposed.")] public void Dispose() { + GC.SuppressFinalize(this); } /// @@ -207,7 +185,8 @@ public void Dispose() /// public ValueTask DisposeAsync() { + GC.SuppressFinalize(this); return default; } } -} \ No newline at end of file +} diff --git a/src/Autofac.Integration.Web/Forms/AttributedInjection.cs b/src/Autofac.Integration.Web/Forms/AttributedInjection.cs index 73f09b4..98ea685 100644 --- a/src/Autofac.Integration.Web/Forms/AttributedInjection.cs +++ b/src/Autofac.Integration.Web/Forms/AttributedInjection.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; @@ -42,24 +20,26 @@ internal class AttributedInjection : PageInjectionBehavior protected override Func GetInjector(IComponentContext context) { if (context == null) + { throw new ArgumentNullException(nameof(context)); + } return target => - { - var targetType = target.GetType(); - if (targetType.GetCustomAttributes(typeof(InjectPropertiesAttribute), true).Length > 0) - { - return context.InjectProperties(target); - } - else if (targetType.GetCustomAttributes(typeof(InjectUnsetPropertiesAttribute), true).Length > 0) - { - return context.InjectUnsetProperties(target); - } - else - { - return target; - } - }; + { + var targetType = target.GetType(); + if (targetType.GetCustomAttributes(typeof(InjectPropertiesAttribute), true).Length > 0) + { + return context.InjectProperties(target); + } + else if (targetType.GetCustomAttributes(typeof(InjectUnsetPropertiesAttribute), true).Length > 0) + { + return context.InjectUnsetProperties(target); + } + else + { + return target; + } + }; } } } diff --git a/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs b/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs index 5c1e63e..fc727a2 100644 --- a/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; @@ -34,17 +12,19 @@ namespace Autofac.Integration.Web.Forms /// public class AttributedInjectionModule : DependencyInjectionModule { - private IInjectionBehavior _attributedInjection = new AttributedInjection(); + private readonly IInjectionBehavior _attributedInjection = new AttributedInjection(); /// - /// Override to customise injection behavior based on HTTP Handler type. + /// Override to customize injection behavior based on HTTP Handler type. /// /// Type of the handler. /// The injection behavior. protected override IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType) { if (handlerType == null) + { throw new ArgumentNullException(nameof(handlerType)); + } return _attributedInjection; } diff --git a/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs b/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs index 2fe0e6e..f9c97ea 100644 --- a/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; diff --git a/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs b/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs index 9701e5b..cb0946f 100644 --- a/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Web; @@ -33,8 +11,8 @@ namespace Autofac.Integration.Web.Forms /// public abstract class DependencyInjectionModule : IHttpModule { - private IContainerProviderAccessor _containerProviderAccessor; - private HttpApplication _httpApplication; + private IContainerProviderAccessor? _containerProviderAccessor; + private HttpApplication? _httpApplication; /// /// Disposes of the resources (other than memory) used by the module that implements . @@ -53,7 +31,9 @@ public void Init(HttpApplication context) _containerProviderAccessor = context as IContainerProviderAccessor; if (_containerProviderAccessor == null) + { throw new InvalidOperationException(DependencyInjectionModuleResources.ApplicationMustImplementAccessor); + } context.PreRequestHandlerExecute += OnPreRequestHandlerExecute; } @@ -66,13 +46,16 @@ public void Init(HttpApplication context) /// The instance containing the event data. private void OnPreRequestHandlerExecute(object sender, EventArgs e) { - var handler = _httpApplication.Context.CurrentHandler; + var handler = _httpApplication?.Context.CurrentHandler; if (handler != null) { var injectionBehavior = GetInjectionBehavior(handler); - var cp = _containerProviderAccessor.ContainerProvider; + var cp = _containerProviderAccessor?.ContainerProvider; if (cp == null) + { throw new InvalidOperationException(ContainerDisposalModuleResources.ContainerProviderNull); + } + injectionBehavior.InjectDependencies(cp.RequestLifetime, handler); } } @@ -85,7 +68,9 @@ private void OnPreRequestHandlerExecute(object sender, EventArgs e) protected internal IInjectionBehavior GetInjectionBehavior(IHttpHandler handler) { if (handler == null) + { throw new ArgumentNullException(nameof(handler)); + } if (handler is DefaultHttpHandler) { diff --git a/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs b/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs index 1be16c1..8e62b70 100644 --- a/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs +++ b/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. namespace Autofac.Integration.Web.Forms { diff --git a/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs b/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs index 71612b0..0b48130 100644 --- a/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; diff --git a/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs b/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs index d99aef8..82f623b 100644 --- a/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; diff --git a/src/Autofac.Integration.Web/Forms/NoInjection.cs b/src/Autofac.Integration.Web/Forms/NoInjection.cs index 5e59165..dae0f07 100644 --- a/src/Autofac.Integration.Web/Forms/NoInjection.cs +++ b/src/Autofac.Integration.Web/Forms/NoInjection.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. namespace Autofac.Integration.Web.Forms { diff --git a/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs b/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs index f831765..9d52da2 100644 --- a/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs +++ b/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs @@ -1,27 +1,5 @@ -// Contributed by // This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Web.UI; @@ -41,10 +19,14 @@ internal abstract class PageInjectionBehavior : IInjectionBehavior public void InjectDependencies(IComponentContext context, object target) { if (context == null) + { throw new ArgumentNullException(nameof(context)); + } if (target == null) + { throw new ArgumentNullException(nameof(target)); + } var injector = GetInjector(context); @@ -66,32 +48,47 @@ public void InjectDependencies(IComponentContext context, object target) private static void DoInjection(Func injector, object target) { if (injector == null) + { throw new ArgumentNullException(nameof(injector)); + } if (target == null) + { throw new ArgumentNullException(nameof(target)); + } injector(target); if (target is Page page) + { page.PreLoad += (s, e) => InjectUserControls(injector, page); + } } private static void InjectUserControls(Func injector, Control parent) { if (injector == null) + { throw new ArgumentNullException(nameof(injector)); + } if (parent == null) + { throw new ArgumentNullException(nameof(parent)); + } if (parent.Controls == null) + { return; + } foreach (Control control in parent.Controls) { if (control is UserControl uc) + { injector(uc); + } + InjectUserControls(injector, control); } } diff --git a/src/Autofac.Integration.Web/Forms/PropertyInjection.cs b/src/Autofac.Integration.Web/Forms/PropertyInjection.cs index 892df67..1a8fcb3 100644 --- a/src/Autofac.Integration.Web/Forms/PropertyInjection.cs +++ b/src/Autofac.Integration.Web/Forms/PropertyInjection.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; @@ -40,7 +18,9 @@ internal class PropertyInjection : PageInjectionBehavior protected override Func GetInjector(IComponentContext context) { if (context == null) + { throw new ArgumentNullException(nameof(context)); + } return context.InjectProperties; } diff --git a/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs b/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs index 614efeb..99c9ad3 100644 --- a/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; @@ -33,17 +11,19 @@ namespace Autofac.Integration.Web.Forms /// public class PropertyInjectionModule : DependencyInjectionModule { - private IInjectionBehavior _injectProperties = new PropertyInjection(); + private readonly IInjectionBehavior _injectProperties = new PropertyInjection(); /// - /// Override to customise injection behavior based on HTTP Handler type. + /// Override to customize injection behavior based on HTTP Handler type. /// /// Type of the handler. /// The injection behavior. protected override IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType) { if (handlerType == null) + { throw new ArgumentNullException(nameof(handlerType)); + } return _injectProperties; } diff --git a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs index b01f66c..0f521f5 100644 --- a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs +++ b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; @@ -40,7 +18,9 @@ internal class UnsetPropertyInjection : PageInjectionBehavior protected override Func GetInjector(IComponentContext context) { if (context == null) + { throw new ArgumentNullException(nameof(context)); + } return context.InjectUnsetProperties; } diff --git a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs index 78ce586..87ba878 100644 --- a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; @@ -33,17 +11,19 @@ namespace Autofac.Integration.Web.Forms /// public class UnsetPropertyInjectionModule : DependencyInjectionModule { - private IInjectionBehavior _injectUnsetProperties = new UnsetPropertyInjection(); + private readonly IInjectionBehavior _injectUnsetProperties = new UnsetPropertyInjection(); /// - /// Override to customise injection behavior based on HTTP Handler type. + /// Override to customize injection behavior based on HTTP Handler type. /// /// Type of the handler. /// The injection behavior. protected override IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType) { if (handlerType == null) + { throw new ArgumentNullException(nameof(handlerType)); + } return _injectUnsetProperties; } diff --git a/src/Autofac.Integration.Web/IContainerProvider.cs b/src/Autofac.Integration.Web/IContainerProvider.cs index 66c1a67..be3788a 100644 --- a/src/Autofac.Integration.Web/IContainerProvider.cs +++ b/src/Autofac.Integration.Web/IContainerProvider.cs @@ -1,26 +1,5 @@ -// Contributed by Nicholas Blumhardt 2008-01-28 -// Copyright © 2011 Autofac Contributors -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System.Threading.Tasks; diff --git a/src/Autofac.Integration.Web/IContainerProviderAccessor.cs b/src/Autofac.Integration.Web/IContainerProviderAccessor.cs index b5d3956..7333c31 100644 --- a/src/Autofac.Integration.Web/IContainerProviderAccessor.cs +++ b/src/Autofac.Integration.Web/IContainerProviderAccessor.cs @@ -1,26 +1,5 @@ -// Contributed by Nicholas Blumhardt 2008-01-28 -// Copyright © 2011 Autofac Contributors -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. namespace Autofac.Integration.Web { diff --git a/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs b/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs index ca8468d..a22b12a 100644 --- a/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs +++ b/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; diff --git a/src/Autofac.Integration.Web/RegistrationExtensions.cs b/src/Autofac.Integration.Web/RegistrationExtensions.cs index 7201005..e4dff37 100644 --- a/src/Autofac.Integration.Web/RegistrationExtensions.cs +++ b/src/Autofac.Integration.Web/RegistrationExtensions.cs @@ -1,27 +1,5 @@ -// This software is part of the Autofac IoC container -// Copyright © 2011 Autofac Contributors -// https://autofac.org -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Diagnostics.CodeAnalysis; @@ -79,7 +57,10 @@ public static IRegistrationBuilder - net472 $(NoWarn);CS1591 @@ -28,12 +27,18 @@ runtime; build; native; contentfiles; analyzers + + + + + + - \ No newline at end of file + diff --git a/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs b/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs index 817b5c0..6283989 100644 --- a/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs +++ b/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +using System; using System.Web; using Autofac.Integration.Web.Forms; using Xunit; @@ -113,4 +116,4 @@ private IComponentContext CreateContext() return cb.Build(); } } -} \ No newline at end of file +} diff --git a/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs b/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs index 9694d84..27060b1 100644 --- a/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs +++ b/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs @@ -1,4 +1,7 @@ -using System.IO; +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +using System.IO; using System.Reflection; using System.Web; using System.Web.SessionState; From 9dbfac5195708c12a6a31436f63f89ebc9b0af32 Mon Sep 17 00:00:00 2001 From: Travis Illig Date: Thu, 21 Jul 2022 14:10:28 -0700 Subject: [PATCH 3/5] Remove unnecessary usings. --- src/Autofac.Integration.Web/ContainerDisposalModule.cs | 2 -- src/Autofac.Integration.Web/ContainerProvider.cs | 2 -- src/Autofac.Integration.Web/ContainerProviderContainer.cs | 3 --- src/Autofac.Integration.Web/Forms/AttributedInjection.cs | 2 -- src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs | 2 -- .../Forms/DependencyInjectionAttribute.cs | 2 -- src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs | 1 - src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs | 2 -- .../Forms/InjectUnsetPropertiesAttribute.cs | 2 -- src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs | 1 - src/Autofac.Integration.Web/Forms/PropertyInjection.cs | 2 -- src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs | 2 -- src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs | 2 -- .../Forms/UnsetPropertyInjectionModule.cs | 2 -- src/Autofac.Integration.Web/IContainerProvider.cs | 2 -- src/Autofac.Integration.Web/Properties/AssemblyInfo.cs | 3 --- src/Autofac.Integration.Web/RegistrationExtensions.cs | 2 -- src/Autofac.Integration.Web/WebLifetime.cs | 1 - .../Forms/AttributedInjectionModuleFixture.cs | 2 -- .../RegistrationExtensionsFixture.cs | 2 -- 20 files changed, 39 deletions(-) diff --git a/src/Autofac.Integration.Web/ContainerDisposalModule.cs b/src/Autofac.Integration.Web/ContainerDisposalModule.cs index 147fa98..fffa8f1 100644 --- a/src/Autofac.Integration.Web/ContainerDisposalModule.cs +++ b/src/Autofac.Integration.Web/ContainerDisposalModule.cs @@ -1,9 +1,7 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; using System.Diagnostics.CodeAnalysis; -using System.Threading.Tasks; using System.Web; namespace Autofac.Integration.Web diff --git a/src/Autofac.Integration.Web/ContainerProvider.cs b/src/Autofac.Integration.Web/ContainerProvider.cs index f6ae405..e261d09 100644 --- a/src/Autofac.Integration.Web/ContainerProvider.cs +++ b/src/Autofac.Integration.Web/ContainerProvider.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; -using System.Threading.Tasks; using System.Web; using Autofac.Core.Lifetime; diff --git a/src/Autofac.Integration.Web/ContainerProviderContainer.cs b/src/Autofac.Integration.Web/ContainerProviderContainer.cs index 893e2e5..e8da0ed 100644 --- a/src/Autofac.Integration.Web/ContainerProviderContainer.cs +++ b/src/Autofac.Integration.Web/ContainerProviderContainer.cs @@ -1,11 +1,8 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; -using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Threading.Tasks; using Autofac.Builder; using Autofac.Core; using Autofac.Core.Lifetime; diff --git a/src/Autofac.Integration.Web/Forms/AttributedInjection.cs b/src/Autofac.Integration.Web/Forms/AttributedInjection.cs index 98ea685..5990cb6 100644 --- a/src/Autofac.Integration.Web/Forms/AttributedInjection.cs +++ b/src/Autofac.Integration.Web/Forms/AttributedInjection.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; - namespace Autofac.Integration.Web.Forms { /// diff --git a/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs b/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs index fc727a2..49d58fe 100644 --- a/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; - namespace Autofac.Integration.Web.Forms { /// diff --git a/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs b/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs index f9c97ea..04dba58 100644 --- a/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; - namespace Autofac.Integration.Web.Forms { /// diff --git a/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs b/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs index cb0946f..6302652 100644 --- a/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs @@ -1,7 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; using System.Web; namespace Autofac.Integration.Web.Forms diff --git a/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs b/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs index 0b48130..723eee4 100644 --- a/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; - namespace Autofac.Integration.Web.Forms { /// diff --git a/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs b/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs index 82f623b..941c770 100644 --- a/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; - namespace Autofac.Integration.Web.Forms { /// diff --git a/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs b/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs index 9d52da2..8b23660 100644 --- a/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs +++ b/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs @@ -1,7 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; using System.Web.UI; namespace Autofac.Integration.Web.Forms diff --git a/src/Autofac.Integration.Web/Forms/PropertyInjection.cs b/src/Autofac.Integration.Web/Forms/PropertyInjection.cs index 1a8fcb3..5d183ec 100644 --- a/src/Autofac.Integration.Web/Forms/PropertyInjection.cs +++ b/src/Autofac.Integration.Web/Forms/PropertyInjection.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; - namespace Autofac.Integration.Web.Forms { /// diff --git a/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs b/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs index 99c9ad3..1291269 100644 --- a/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; - namespace Autofac.Integration.Web.Forms { /// diff --git a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs index 0f521f5..4415b48 100644 --- a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs +++ b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; - namespace Autofac.Integration.Web.Forms { /// diff --git a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs index 87ba878..f20bee8 100644 --- a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; - namespace Autofac.Integration.Web.Forms { /// diff --git a/src/Autofac.Integration.Web/IContainerProvider.cs b/src/Autofac.Integration.Web/IContainerProvider.cs index be3788a..ff6b839 100644 --- a/src/Autofac.Integration.Web/IContainerProvider.cs +++ b/src/Autofac.Integration.Web/IContainerProvider.cs @@ -1,8 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System.Threading.Tasks; - namespace Autofac.Integration.Web { /// diff --git a/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs b/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs index a22b12a..2ee8058 100644 --- a/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs +++ b/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs @@ -1,9 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; -using System.Reflection; -using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Autofac.Integration.Web/RegistrationExtensions.cs b/src/Autofac.Integration.Web/RegistrationExtensions.cs index e4dff37..ca3d536 100644 --- a/src/Autofac.Integration.Web/RegistrationExtensions.cs +++ b/src/Autofac.Integration.Web/RegistrationExtensions.cs @@ -1,9 +1,7 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Web; using Autofac.Builder; using Autofac.Core; diff --git a/src/Autofac.Integration.Web/WebLifetime.cs b/src/Autofac.Integration.Web/WebLifetime.cs index 4a11698..ee4bb06 100644 --- a/src/Autofac.Integration.Web/WebLifetime.cs +++ b/src/Autofac.Integration.Web/WebLifetime.cs @@ -1,7 +1,6 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; using Autofac.Core.Lifetime; namespace Autofac.Integration.Web diff --git a/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs b/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs index 6283989..f35067a 100644 --- a/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs +++ b/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs @@ -1,10 +1,8 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System; using System.Web; using Autofac.Integration.Web.Forms; -using Xunit; namespace Autofac.Integration.Web.Test.Forms { diff --git a/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs b/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs index 27060b1..e24298a 100644 --- a/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs +++ b/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs @@ -1,11 +1,9 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -using System.IO; using System.Reflection; using System.Web; using System.Web.SessionState; -using Xunit; namespace Autofac.Integration.Web.Test { From db417893a7e9cb971837d2f74c22846d2bc36f70 Mon Sep 17 00:00:00 2001 From: Travis Illig Date: Thu, 21 Jul 2022 14:11:22 -0700 Subject: [PATCH 4/5] File-scoped namespaces. --- .../ContainerDisposalModule.cs | 99 +++--- .../ContainerProvider.cs | 129 ++++---- .../ContainerProviderContainer.cs | 307 +++++++++--------- .../Forms/AttributedInjection.cs | 59 ++-- .../Forms/AttributedInjectionModule.cs | 37 +-- .../Forms/DependencyInjectionAttribute.cs | 15 +- .../Forms/DependencyInjectionModule.cs | 155 +++++---- .../Forms/IInjectionBehavior.cs | 21 +- .../Forms/InjectPropertiesAttribute.cs | 15 +- .../Forms/InjectUnsetPropertiesAttribute.cs | 17 +- .../Forms/NoInjection.cs | 21 +- .../Forms/PageInjectionBehavior.cs | 129 ++++---- .../Forms/PropertyInjection.cs | 29 +- .../Forms/PropertyInjectionModule.cs | 35 +- .../Forms/UnsetPropertyInjection.cs | 29 +- .../Forms/UnsetPropertyInjectionModule.cs | 35 +- .../IContainerProvider.cs | 39 ++- .../IContainerProviderAccessor.cs | 21 +- .../RegistrationExtensions.cs | 147 +++++---- src/Autofac.Integration.Web/WebLifetime.cs | 19 +- .../Forms/AttributedInjectionModuleFixture.cs | 183 ++++++----- .../RegistrationExtensionsFixture.cs | 115 ++++--- 22 files changed, 817 insertions(+), 839 deletions(-) diff --git a/src/Autofac.Integration.Web/ContainerDisposalModule.cs b/src/Autofac.Integration.Web/ContainerDisposalModule.cs index fffa8f1..768b1de 100644 --- a/src/Autofac.Integration.Web/ContainerDisposalModule.cs +++ b/src/Autofac.Integration.Web/ContainerDisposalModule.cs @@ -4,72 +4,71 @@ using System.Diagnostics.CodeAnalysis; using System.Web; -namespace Autofac.Integration.Web +namespace Autofac.Integration.Web; + +/// +/// HTTP Module that disposes of Autofac-created components when processing for +/// a request completes. +/// +public class ContainerDisposalModule : IHttpModule { + private IContainerProviderAccessor? _containerProviderAccessor; + /// - /// HTTP Module that disposes of Autofac-created components when processing for - /// a request completes. + /// Disposes of the resources (other than memory) used by the module that implements . /// - public class ContainerDisposalModule : IHttpModule + public void Dispose() { - private IContainerProviderAccessor? _containerProviderAccessor; + } - /// - /// Disposes of the resources (other than memory) used by the module that implements . - /// - public void Dispose() + /// + /// Initializes a module and prepares it to handle requests. + /// + /// An that provides access to the methods, properties, and events common to all application objects within an ASP.NET application. + public void Init(HttpApplication context) + { + if (context == null) { + throw new ArgumentNullException(nameof(context)); } - /// - /// Initializes a module and prepares it to handle requests. - /// - /// An that provides access to the methods, properties, and events common to all application objects within an ASP.NET application. - public void Init(HttpApplication context) + _containerProviderAccessor = context as IContainerProviderAccessor; + if (_containerProviderAccessor == null) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - _containerProviderAccessor = context as IContainerProviderAccessor; - if (_containerProviderAccessor == null) - { - throw new InvalidOperationException(ContainerDisposalModuleResources.ApplicationMustImplementAccessor); - } + throw new InvalidOperationException(ContainerDisposalModuleResources.ApplicationMustImplementAccessor); + } - var wrapper = new EventHandlerTaskAsyncHelper(OnEndRequest); + var wrapper = new EventHandlerTaskAsyncHelper(OnEndRequest); - context.AddOnEndRequestAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler); - } + context.AddOnEndRequestAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler); + } - /// - /// Dispose of the per-request container. - /// - [SuppressMessage("CA1849", "CA1849", Justification = "If the value task is already completed, getting the result synchronously isn't a problem.")] - private Task OnEndRequest(object sender, EventArgs e) + /// + /// Dispose of the per-request container. + /// + [SuppressMessage("CA1849", "CA1849", Justification = "If the value task is already completed, getting the result synchronously isn't a problem.")] + private Task OnEndRequest(object sender, EventArgs e) + { + var cp = _containerProviderAccessor?.ContainerProvider; + if (cp == null) { - var cp = _containerProviderAccessor?.ContainerProvider; - if (cp == null) - { - throw new InvalidOperationException(ContainerDisposalModuleResources.ContainerProviderNull); - } + throw new InvalidOperationException(ContainerDisposalModuleResources.ContainerProviderNull); + } - var valueTask = cp.EndRequestLifetime(); + var valueTask = cp.EndRequestLifetime(); - // https://github.com/dotnet/aspnetcore/blob/main/src/Shared/ValueTaskExtensions/ValueTaskExtensions.cs#L13 + // https://github.com/dotnet/aspnetcore/blob/main/src/Shared/ValueTaskExtensions/ValueTaskExtensions.cs#L13 - // Try to avoid the allocation from AsTask - if (valueTask.IsCompletedSuccessfully) - { - // Signal consumption to the IValueTaskSource - valueTask.GetAwaiter().GetResult(); - return Task.CompletedTask; - } - else - { - return valueTask.AsTask(); - } + // Try to avoid the allocation from AsTask + if (valueTask.IsCompletedSuccessfully) + { + // Signal consumption to the IValueTaskSource + valueTask.GetAwaiter().GetResult(); + return Task.CompletedTask; + } + else + { + return valueTask.AsTask(); } } } diff --git a/src/Autofac.Integration.Web/ContainerProvider.cs b/src/Autofac.Integration.Web/ContainerProvider.cs index e261d09..0ba3dc2 100644 --- a/src/Autofac.Integration.Web/ContainerProvider.cs +++ b/src/Autofac.Integration.Web/ContainerProvider.cs @@ -4,87 +4,86 @@ using System.Web; using Autofac.Core.Lifetime; -namespace Autofac.Integration.Web +namespace Autofac.Integration.Web; + +/// +/// Provides application-wide and per-request containers. +/// +public class ContainerProvider : IContainerProvider { + private readonly Action? _requestLifetimeConfiguration; + /// - /// Provides application-wide and per-request containers. + /// Initializes a new instance of the class. /// - public class ContainerProvider : IContainerProvider + /// The application container. + public ContainerProvider(IContainer applicationContainer) { - private readonly Action? _requestLifetimeConfiguration; - - /// - /// Initializes a new instance of the class. - /// - /// The application container. - public ContainerProvider(IContainer applicationContainer) - { - ApplicationContainer = applicationContainer ?? throw new ArgumentNullException(nameof(applicationContainer)); - } + ApplicationContainer = applicationContainer ?? throw new ArgumentNullException(nameof(applicationContainer)); + } - /// - /// Initializes a new instance of the class. - /// - /// The application container. - /// - /// An action that will be executed when building - /// the per-request lifetime. The components visible within the request can be - /// customized here. - /// - public ContainerProvider(IContainer applicationContainer, Action requestLifetimeConfiguration) - : this(applicationContainer) - { - _requestLifetimeConfiguration = requestLifetimeConfiguration ?? throw new ArgumentNullException(nameof(requestLifetimeConfiguration)); - } + /// + /// Initializes a new instance of the class. + /// + /// The application container. + /// + /// An action that will be executed when building + /// the per-request lifetime. The components visible within the request can be + /// customized here. + /// + public ContainerProvider(IContainer applicationContainer, Action requestLifetimeConfiguration) + : this(applicationContainer) + { + _requestLifetimeConfiguration = requestLifetimeConfiguration ?? throw new ArgumentNullException(nameof(requestLifetimeConfiguration)); + } - /// - /// Dispose of the current request's container, if it has been - /// instantiated. - /// - public ValueTask EndRequestLifetime() - { - var rc = AmbientRequestLifetime; - return rc == null ? default : rc.DisposeAsync(); - } + /// + /// Dispose of the current request's container, if it has been + /// instantiated. + /// + public ValueTask EndRequestLifetime() + { + var rc = AmbientRequestLifetime; + return rc == null ? default : rc.DisposeAsync(); + } - /// - /// Gets the global, application-wide container. - /// - public IContainer ApplicationContainer { get; } + /// + /// Gets the global, application-wide container. + /// + public IContainer ApplicationContainer { get; } - /// - /// Gets the container used to manage components for processing the - /// current request. - /// - public ILifetimeScope RequestLifetime + /// + /// Gets the container used to manage components for processing the + /// current request. + /// + public ILifetimeScope RequestLifetime + { + get { - get + var result = AmbientRequestLifetime; + if (result == null) { - var result = AmbientRequestLifetime; - if (result == null) - { - result = _requestLifetimeConfiguration == null ? - ApplicationContainer.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag) : - ApplicationContainer.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag, _requestLifetimeConfiguration); + result = _requestLifetimeConfiguration == null ? + ApplicationContainer.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag) : + ApplicationContainer.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag, _requestLifetimeConfiguration); - AmbientRequestLifetime = result; - } - - return result; + AmbientRequestLifetime = result; } + + return result; } + } - private static ILifetimeScope AmbientRequestLifetime + private static ILifetimeScope AmbientRequestLifetime + { + get { - get - { - return (ILifetimeScope)HttpContext.Current.Items[typeof(ILifetimeScope)]; - } + return (ILifetimeScope)HttpContext.Current.Items[typeof(ILifetimeScope)]; + } - set - { - HttpContext.Current.Items[typeof(ILifetimeScope)] = value; - } + set + { + HttpContext.Current.Items[typeof(ILifetimeScope)] = value; } } } diff --git a/src/Autofac.Integration.Web/ContainerProviderContainer.cs b/src/Autofac.Integration.Web/ContainerProviderContainer.cs index e8da0ed..19008d9 100644 --- a/src/Autofac.Integration.Web/ContainerProviderContainer.cs +++ b/src/Autofac.Integration.Web/ContainerProviderContainer.cs @@ -9,181 +9,180 @@ using Autofac.Core.Registration; using Autofac.Core.Resolving; -namespace Autofac.Integration.Web +namespace Autofac.Integration.Web; + +/// +/// Provides an implementation of which uses the configured +/// to route calls to the current request container. +/// +[DebuggerDisplay("Tag = {Tag}")] +[SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Disposing of this wrapper container should not result in the whole application container being disposed.")] +public class ContainerProviderContainer : IContainer { + private readonly IContainerProvider _containerProvider; + /// - /// Provides an implementation of which uses the configured - /// to route calls to the current request container. + /// Initializes a new instance of the class. /// - [DebuggerDisplay("Tag = {Tag}")] - [SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Disposing of this wrapper container should not result in the whole application container being disposed.")] - public class ContainerProviderContainer : IContainer + /// The to use to retrieve the current request container. + public ContainerProviderContainer(IContainerProvider containerProvider) { - private readonly IContainerProvider _containerProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The to use to retrieve the current request container. - public ContainerProviderContainer(IContainerProvider containerProvider) - { - _containerProvider = containerProvider ?? throw new ArgumentNullException(nameof(containerProvider)); - } + _containerProvider = containerProvider ?? throw new ArgumentNullException(nameof(containerProvider)); + } - /// - /// Gets the registry that associates services with the components that provide them. - /// - public IComponentRegistry ComponentRegistry + /// + /// Gets the registry that associates services with the components that provide them. + /// + public IComponentRegistry ComponentRegistry + { + get { - get - { - return _containerProvider.RequestLifetime.ComponentRegistry; - } + return _containerProvider.RequestLifetime.ComponentRegistry; } + } - /// - public DiagnosticListener DiagnosticSource => _containerProvider.ApplicationContainer.DiagnosticSource; + /// + public DiagnosticListener DiagnosticSource => _containerProvider.ApplicationContainer.DiagnosticSource; - /// - /// Begin a new nested scope. Component instances created via the new scope - /// will be disposed along with it. - /// - /// A new lifetime scope. - public ILifetimeScope BeginLifetimeScope() - { - return _containerProvider.RequestLifetime.BeginLifetimeScope(); - } + /// + /// Begin a new nested scope. Component instances created via the new scope + /// will be disposed along with it. + /// + /// A new lifetime scope. + public ILifetimeScope BeginLifetimeScope() + { + return _containerProvider.RequestLifetime.BeginLifetimeScope(); + } - /// - /// Begin a new nested scope. Component instances created via the new scope - /// will be disposed along with it. - /// - /// The tag applied to the . - /// A new lifetime scope. - public ILifetimeScope BeginLifetimeScope(object tag) - { - return _containerProvider.RequestLifetime.BeginLifetimeScope(tag); - } + /// + /// Begin a new nested scope. Component instances created via the new scope + /// will be disposed along with it. + /// + /// The tag applied to the . + /// A new lifetime scope. + public ILifetimeScope BeginLifetimeScope(object tag) + { + return _containerProvider.RequestLifetime.BeginLifetimeScope(tag); + } - /// - /// Begin a new nested scope, with additional components available to it. - /// Component instances created via the new scope - /// will be disposed along with it. - /// - /// - /// The components registered in the sub-scope will be treated as though they were - /// registered in the root scope, i.e., SingleInstance() components will live as long - /// as the root scope. - /// - /// Action on a - /// that adds component registrations visible only in the new scope. - /// A new lifetime scope. - public ILifetimeScope BeginLifetimeScope(Action configurationAction) - { - return _containerProvider.RequestLifetime.BeginLifetimeScope(configurationAction); - } + /// + /// Begin a new nested scope, with additional components available to it. + /// Component instances created via the new scope + /// will be disposed along with it. + /// + /// + /// The components registered in the sub-scope will be treated as though they were + /// registered in the root scope, i.e., SingleInstance() components will live as long + /// as the root scope. + /// + /// Action on a + /// that adds component registrations visible only in the new scope. + /// A new lifetime scope. + public ILifetimeScope BeginLifetimeScope(Action configurationAction) + { + return _containerProvider.RequestLifetime.BeginLifetimeScope(configurationAction); + } - /// - /// Begin a new nested scope, with additional components available to it. - /// Component instances created via the new scope - /// will be disposed along with it. - /// - /// - /// The components registered in the sub-scope will be treated as though they were - /// registered in the root scope, i.e., SingleInstance() components will live as long - /// as the root scope. - /// - /// The tag applied to the . - /// Action on a - /// that adds component registrations visible only in the new scope. - /// A new lifetime scope. - public ILifetimeScope BeginLifetimeScope(object tag, Action configurationAction) - { - return _containerProvider.RequestLifetime.BeginLifetimeScope(tag, configurationAction); - } + /// + /// Begin a new nested scope, with additional components available to it. + /// Component instances created via the new scope + /// will be disposed along with it. + /// + /// + /// The components registered in the sub-scope will be treated as though they were + /// registered in the root scope, i.e., SingleInstance() components will live as long + /// as the root scope. + /// + /// The tag applied to the . + /// Action on a + /// that adds component registrations visible only in the new scope. + /// A new lifetime scope. + public ILifetimeScope BeginLifetimeScope(object tag, Action configurationAction) + { + return _containerProvider.RequestLifetime.BeginLifetimeScope(tag, configurationAction); + } - /// - /// Gets the disposer associated with this . - /// Component instances can be associated with it manually if required. - /// - /// Typical usage does not require interaction with this member- it - /// is used when extending the container. - public IDisposer Disposer - { - get { return _containerProvider.RequestLifetime.Disposer; } - } + /// + /// Gets the disposer associated with this . + /// Component instances can be associated with it manually if required. + /// + /// Typical usage does not require interaction with this member- it + /// is used when extending the container. + public IDisposer Disposer + { + get { return _containerProvider.RequestLifetime.Disposer; } + } - /// - /// Gets the tag applied to the . - /// - /// Tags allow a level in the lifetime hierarchy to be identified. - /// In most applications, tags are not necessary. - /// - public object Tag + /// + /// Gets the tag applied to the . + /// + /// Tags allow a level in the lifetime hierarchy to be identified. + /// In most applications, tags are not necessary. + /// + public object Tag + { + get { - get - { - return _containerProvider.RequestLifetime.Tag; - } + return _containerProvider.RequestLifetime.Tag; } + } - /// - /// Fired when a new scope based on the current scope is beginning. - /// - public event EventHandler ChildLifetimeScopeBeginning - { - add { _containerProvider.RequestLifetime.ChildLifetimeScopeBeginning += value; } - remove { _containerProvider.RequestLifetime.ChildLifetimeScopeBeginning -= value; } - } + /// + /// Fired when a new scope based on the current scope is beginning. + /// + public event EventHandler ChildLifetimeScopeBeginning + { + add { _containerProvider.RequestLifetime.ChildLifetimeScopeBeginning += value; } + remove { _containerProvider.RequestLifetime.ChildLifetimeScopeBeginning -= value; } + } - /// - /// Fired when this scope is ending. - /// - public event EventHandler CurrentScopeEnding - { - add { _containerProvider.RequestLifetime.CurrentScopeEnding += value; } - remove { _containerProvider.RequestLifetime.CurrentScopeEnding -= value; } - } + /// + /// Fired when this scope is ending. + /// + public event EventHandler CurrentScopeEnding + { + add { _containerProvider.RequestLifetime.CurrentScopeEnding += value; } + remove { _containerProvider.RequestLifetime.CurrentScopeEnding -= value; } + } - /// - /// Fired when a resolve operation is beginning in this scope. - /// - public event EventHandler ResolveOperationBeginning - { - add { _containerProvider.RequestLifetime.ResolveOperationBeginning += value; } - remove { _containerProvider.RequestLifetime.ResolveOperationBeginning -= value; } - } + /// + /// Fired when a resolve operation is beginning in this scope. + /// + public event EventHandler ResolveOperationBeginning + { + add { _containerProvider.RequestLifetime.ResolveOperationBeginning += value; } + remove { _containerProvider.RequestLifetime.ResolveOperationBeginning -= value; } + } - /// - /// Resolve an instance of the provided registration within the context. - /// - /// The resolve request. - /// - /// The component instance. - /// - /// - /// - public object ResolveComponent(ResolveRequest request) - { - return _containerProvider.RequestLifetime.ResolveComponent(request); - } + /// + /// Resolve an instance of the provided registration within the context. + /// + /// The resolve request. + /// + /// The component instance. + /// + /// + /// + public object ResolveComponent(ResolveRequest request) + { + return _containerProvider.RequestLifetime.ResolveComponent(request); + } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - GC.SuppressFinalize(this); - } + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + GC.SuppressFinalize(this); + } - /// - /// Performs application-defined tasks associated with freeing, releasing, or - /// resetting unmanaged resources asynchronously. - /// - public ValueTask DisposeAsync() - { - GC.SuppressFinalize(this); - return default; - } + /// + /// Performs application-defined tasks associated with freeing, releasing, or + /// resetting unmanaged resources asynchronously. + /// + public ValueTask DisposeAsync() + { + GC.SuppressFinalize(this); + return default; } } diff --git a/src/Autofac.Integration.Web/Forms/AttributedInjection.cs b/src/Autofac.Integration.Web/Forms/AttributedInjection.cs index 5990cb6..060cbfd 100644 --- a/src/Autofac.Integration.Web/Forms/AttributedInjection.cs +++ b/src/Autofac.Integration.Web/Forms/AttributedInjection.cs @@ -1,43 +1,42 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Injects dependencies into request handlers and pages that have been +/// decorated with the [InjectProperties] or [InjectUnsetProperties] +/// attributes. +/// +internal class AttributedInjection : PageInjectionBehavior { /// - /// Injects dependencies into request handlers and pages that have been - /// decorated with the [InjectProperties] or [InjectUnsetProperties] - /// attributes. + /// Override to return a closure that injects properties into a target. /// - internal class AttributedInjection : PageInjectionBehavior + /// The context. + /// The injector. + protected override Func GetInjector(IComponentContext context) { - /// - /// Override to return a closure that injects properties into a target. - /// - /// The context. - /// The injector. - protected override Func GetInjector(IComponentContext context) + if (context == null) { - if (context == null) + throw new ArgumentNullException(nameof(context)); + } + + return target => + { + var targetType = target.GetType(); + if (targetType.GetCustomAttributes(typeof(InjectPropertiesAttribute), true).Length > 0) { - throw new ArgumentNullException(nameof(context)); + return context.InjectProperties(target); } - - return target => + else if (targetType.GetCustomAttributes(typeof(InjectUnsetPropertiesAttribute), true).Length > 0) { - var targetType = target.GetType(); - if (targetType.GetCustomAttributes(typeof(InjectPropertiesAttribute), true).Length > 0) - { - return context.InjectProperties(target); - } - else if (targetType.GetCustomAttributes(typeof(InjectUnsetPropertiesAttribute), true).Length > 0) - { - return context.InjectUnsetProperties(target); - } - else - { - return target; - } - }; - } + return context.InjectUnsetProperties(target); + } + else + { + return target; + } + }; } } diff --git a/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs b/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs index 49d58fe..6232365 100644 --- a/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs @@ -1,30 +1,29 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Injects dependencies into request handlers and pages that have been +/// decorated with the [InjectProperties] or [InjectUnsetProperties] +/// attributes. +/// +public class AttributedInjectionModule : DependencyInjectionModule { + private readonly IInjectionBehavior _attributedInjection = new AttributedInjection(); + /// - /// Injects dependencies into request handlers and pages that have been - /// decorated with the [InjectProperties] or [InjectUnsetProperties] - /// attributes. + /// Override to customize injection behavior based on HTTP Handler type. /// - public class AttributedInjectionModule : DependencyInjectionModule + /// Type of the handler. + /// The injection behavior. + protected override IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType) { - private readonly IInjectionBehavior _attributedInjection = new AttributedInjection(); - - /// - /// Override to customize injection behavior based on HTTP Handler type. - /// - /// Type of the handler. - /// The injection behavior. - protected override IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType) + if (handlerType == null) { - if (handlerType == null) - { - throw new ArgumentNullException(nameof(handlerType)); - } - - return _attributedInjection; + throw new ArgumentNullException(nameof(handlerType)); } + + return _attributedInjection; } } diff --git a/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs b/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs index 04dba58..6706dbb 100644 --- a/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs @@ -1,13 +1,12 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Base class for dependency injection attributes. +/// +[AttributeUsage(AttributeTargets.Class)] +public abstract class DependencyInjectionAttribute : Attribute { - /// - /// Base class for dependency injection attributes. - /// - [AttributeUsage(AttributeTargets.Class)] - public abstract class DependencyInjectionAttribute : Attribute - { - } } diff --git a/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs b/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs index 6302652..f1178ef 100644 --- a/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs @@ -3,105 +3,104 @@ using System.Web; -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Base for classes that inject dependencies into HTTP Handlers. +/// +public abstract class DependencyInjectionModule : IHttpModule { + private IContainerProviderAccessor? _containerProviderAccessor; + private HttpApplication? _httpApplication; + + /// + /// Disposes of the resources (other than memory) used by the module that implements . + /// + public void Dispose() + { + } + /// - /// Base for classes that inject dependencies into HTTP Handlers. + /// Initializes a module and prepares it to handle requests. /// - public abstract class DependencyInjectionModule : IHttpModule + /// An that provides access to the methods, properties, and events common to all application objects within an ASP.NET application. + public void Init(HttpApplication context) { - private IContainerProviderAccessor? _containerProviderAccessor; - private HttpApplication? _httpApplication; + _httpApplication = context ?? throw new ArgumentNullException(nameof(context)); + _containerProviderAccessor = context as IContainerProviderAccessor; - /// - /// Disposes of the resources (other than memory) used by the module that implements . - /// - public void Dispose() + if (_containerProviderAccessor == null) { + throw new InvalidOperationException(DependencyInjectionModuleResources.ApplicationMustImplementAccessor); } - /// - /// Initializes a module and prepares it to handle requests. - /// - /// An that provides access to the methods, properties, and events common to all application objects within an ASP.NET application. - public void Init(HttpApplication context) - { - _httpApplication = context ?? throw new ArgumentNullException(nameof(context)); - _containerProviderAccessor = context as IContainerProviderAccessor; + context.PreRequestHandlerExecute += OnPreRequestHandlerExecute; + } - if (_containerProviderAccessor == null) + /// + /// Called before the request handler is executed so that dependencies + /// can be injected. + /// + /// The sender. + /// The instance containing the event data. + private void OnPreRequestHandlerExecute(object sender, EventArgs e) + { + var handler = _httpApplication?.Context.CurrentHandler; + if (handler != null) + { + var injectionBehavior = GetInjectionBehavior(handler); + var cp = _containerProviderAccessor?.ContainerProvider; + if (cp == null) { - throw new InvalidOperationException(DependencyInjectionModuleResources.ApplicationMustImplementAccessor); + throw new InvalidOperationException(ContainerDisposalModuleResources.ContainerProviderNull); } - context.PreRequestHandlerExecute += OnPreRequestHandlerExecute; + injectionBehavior.InjectDependencies(cp.RequestLifetime, handler); } + } - /// - /// Called before the request handler is executed so that dependencies - /// can be injected. - /// - /// The sender. - /// The instance containing the event data. - private void OnPreRequestHandlerExecute(object sender, EventArgs e) + /// + /// Internal for testability outside of a web application. + /// + /// The handler on which to inject dependencies. + /// The injection behavior. + protected internal IInjectionBehavior GetInjectionBehavior(IHttpHandler handler) + { + if (handler == null) { - var handler = _httpApplication?.Context.CurrentHandler; - if (handler != null) - { - var injectionBehavior = GetInjectionBehavior(handler); - var cp = _containerProviderAccessor?.ContainerProvider; - if (cp == null) - { - throw new InvalidOperationException(ContainerDisposalModuleResources.ContainerProviderNull); - } - - injectionBehavior.InjectDependencies(cp.RequestLifetime, handler); - } + throw new ArgumentNullException(nameof(handler)); } - /// - /// Internal for testability outside of a web application. - /// - /// The handler on which to inject dependencies. - /// The injection behavior. - protected internal IInjectionBehavior GetInjectionBehavior(IHttpHandler handler) + if (handler is DefaultHttpHandler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } - - if (handler is DefaultHttpHandler) - { - return NoInjection; - } - else - { - var handlerType = handler.GetType(); - return GetInjectionBehaviorForHandlerType(handlerType); - } + return NoInjection; } + else + { + var handlerType = handler.GetType(); + return GetInjectionBehaviorForHandlerType(handlerType); + } + } - /// - /// Gets a behavior that does not inject dependencies. - /// - protected IInjectionBehavior NoInjection { get; } = new NoInjection(); + /// + /// Gets a behavior that does not inject dependencies. + /// + protected IInjectionBehavior NoInjection { get; } = new NoInjection(); - /// - /// Gets a behavior that injects resolvable dependencies. - /// - protected IInjectionBehavior PropertyInjection { get; } = new PropertyInjection(); + /// + /// Gets a behavior that injects resolvable dependencies. + /// + protected IInjectionBehavior PropertyInjection { get; } = new PropertyInjection(); - /// - /// Gets a behavior that injects unset, resolvable dependencies. - /// - protected IInjectionBehavior UnsetPropertyInjection { get; } = new UnsetPropertyInjection(); + /// + /// Gets a behavior that injects unset, resolvable dependencies. + /// + protected IInjectionBehavior UnsetPropertyInjection { get; } = new UnsetPropertyInjection(); - /// - /// Override to customize injection behavior based on HTTP Handler type. - /// - /// Type of the handler. - /// The injection behavior. - protected abstract IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType); - } + /// + /// Override to customize injection behavior based on HTTP Handler type. + /// + /// Type of the handler. + /// The injection behavior. + protected abstract IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType); } diff --git a/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs b/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs index 8e62b70..ca73c35 100644 --- a/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs +++ b/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs @@ -1,18 +1,17 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Provides dependency injection for a request handler. +/// +public interface IInjectionBehavior { /// - /// Provides dependency injection for a request handler. + /// Inject dependencies in the required fashion. /// - public interface IInjectionBehavior - { - /// - /// Inject dependencies in the required fashion. - /// - /// The context. - /// The target. - void InjectDependencies(IComponentContext context, object target); - } + /// The context. + /// The target. + void InjectDependencies(IComponentContext context, object target); } diff --git a/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs b/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs index 723eee4..bad0b67 100644 --- a/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs @@ -1,13 +1,12 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Indicates that property injection should be performed on the instance when it is instantiated. +/// +[AttributeUsage(AttributeTargets.Class)] +public sealed class InjectPropertiesAttribute : DependencyInjectionAttribute { - /// - /// Indicates that property injection should be performed on the instance when it is instantiated. - /// - [AttributeUsage(AttributeTargets.Class)] - public sealed class InjectPropertiesAttribute : DependencyInjectionAttribute - { - } } diff --git a/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs b/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs index 941c770..5d778b5 100644 --- a/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs @@ -1,14 +1,13 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Indicates that property injection should be performed for null-valued +/// properties on the instance when it is instantiated. +/// +[AttributeUsage(AttributeTargets.Class)] +public sealed class InjectUnsetPropertiesAttribute : DependencyInjectionAttribute { - /// - /// Indicates that property injection should be performed for null-valued - /// properties on the instance when it is instantiated. - /// - [AttributeUsage(AttributeTargets.Class)] - public sealed class InjectUnsetPropertiesAttribute : DependencyInjectionAttribute - { - } } diff --git a/src/Autofac.Integration.Web/Forms/NoInjection.cs b/src/Autofac.Integration.Web/Forms/NoInjection.cs index dae0f07..d66dfa5 100644 --- a/src/Autofac.Integration.Web/Forms/NoInjection.cs +++ b/src/Autofac.Integration.Web/Forms/NoInjection.cs @@ -1,20 +1,19 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Does not inject properties. +/// +internal class NoInjection : IInjectionBehavior { /// - /// Does not inject properties. + /// Inject dependencies in the required fashion. /// - internal class NoInjection : IInjectionBehavior + /// The context. + /// The target. + public void InjectDependencies(IComponentContext context, object target) { - /// - /// Inject dependencies in the required fashion. - /// - /// The context. - /// The target. - public void InjectDependencies(IComponentContext context, object target) - { - } } } diff --git a/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs b/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs index 8b23660..eda01cc 100644 --- a/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs +++ b/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs @@ -3,93 +3,92 @@ using System.Web.UI; -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Assists with the construction of page injectors. +/// +internal abstract class PageInjectionBehavior : IInjectionBehavior { /// - /// Assists with the construction of page injectors. + /// Inject dependencies in the required fashion. /// - internal abstract class PageInjectionBehavior : IInjectionBehavior + /// The context. + /// The target. + public void InjectDependencies(IComponentContext context, object target) { - /// - /// Inject dependencies in the required fashion. - /// - /// The context. - /// The target. - public void InjectDependencies(IComponentContext context, object target) + if (context == null) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + throw new ArgumentNullException(nameof(context)); + } - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + var injector = GetInjector(context); + + DoInjection(injector, target); + } - var injector = GetInjector(context); + /// + /// Override to return a closure that injects properties into a target. + /// + /// The context. + /// The injector. + protected abstract Func GetInjector(IComponentContext context); - DoInjection(injector, target); + /// + /// Does the injection using a supplied injection function. + /// + /// The injector. + /// The target. + private static void DoInjection(Func injector, object target) + { + if (injector == null) + { + throw new ArgumentNullException(nameof(injector)); } - /// - /// Override to return a closure that injects properties into a target. - /// - /// The context. - /// The injector. - protected abstract Func GetInjector(IComponentContext context); - - /// - /// Does the injection using a supplied injection function. - /// - /// The injector. - /// The target. - private static void DoInjection(Func injector, object target) + if (target == null) { - if (injector == null) - { - throw new ArgumentNullException(nameof(injector)); - } + throw new ArgumentNullException(nameof(target)); + } - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } + injector(target); - injector(target); + if (target is Page page) + { + page.PreLoad += (s, e) => InjectUserControls(injector, page); + } + } - if (target is Page page) - { - page.PreLoad += (s, e) => InjectUserControls(injector, page); - } + private static void InjectUserControls(Func injector, Control parent) + { + if (injector == null) + { + throw new ArgumentNullException(nameof(injector)); } - private static void InjectUserControls(Func injector, Control parent) + if (parent == null) { - if (injector == null) - { - throw new ArgumentNullException(nameof(injector)); - } + throw new ArgumentNullException(nameof(parent)); + } - if (parent == null) - { - throw new ArgumentNullException(nameof(parent)); - } + if (parent.Controls == null) + { + return; + } - if (parent.Controls == null) + foreach (Control control in parent.Controls) + { + if (control is UserControl uc) { - return; + injector(uc); } - foreach (Control control in parent.Controls) - { - if (control is UserControl uc) - { - injector(uc); - } - - InjectUserControls(injector, control); - } + InjectUserControls(injector, control); } } } diff --git a/src/Autofac.Integration.Web/Forms/PropertyInjection.cs b/src/Autofac.Integration.Web/Forms/PropertyInjection.cs index 5d183ec..58d9fdf 100644 --- a/src/Autofac.Integration.Web/Forms/PropertyInjection.cs +++ b/src/Autofac.Integration.Web/Forms/PropertyInjection.cs @@ -1,26 +1,25 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Injects any resolvable properties. +/// +internal class PropertyInjection : PageInjectionBehavior { /// - /// Injects any resolvable properties. + /// Override to return a closure that injects properties into a target. /// - internal class PropertyInjection : PageInjectionBehavior + /// The context. + /// The injector. + protected override Func GetInjector(IComponentContext context) { - /// - /// Override to return a closure that injects properties into a target. - /// - /// The context. - /// The injector. - protected override Func GetInjector(IComponentContext context) + if (context == null) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - return context.InjectProperties; + throw new ArgumentNullException(nameof(context)); } + + return context.InjectProperties; } } diff --git a/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs b/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs index 1291269..7fec831 100644 --- a/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs @@ -1,29 +1,28 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Dependency injection module that will always inject any resolvable +/// properties. +/// +public class PropertyInjectionModule : DependencyInjectionModule { + private readonly IInjectionBehavior _injectProperties = new PropertyInjection(); + /// - /// Dependency injection module that will always inject any resolvable - /// properties. + /// Override to customize injection behavior based on HTTP Handler type. /// - public class PropertyInjectionModule : DependencyInjectionModule + /// Type of the handler. + /// The injection behavior. + protected override IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType) { - private readonly IInjectionBehavior _injectProperties = new PropertyInjection(); - - /// - /// Override to customize injection behavior based on HTTP Handler type. - /// - /// Type of the handler. - /// The injection behavior. - protected override IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType) + if (handlerType == null) { - if (handlerType == null) - { - throw new ArgumentNullException(nameof(handlerType)); - } - - return _injectProperties; + throw new ArgumentNullException(nameof(handlerType)); } + + return _injectProperties; } } diff --git a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs index 4415b48..70608c0 100644 --- a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs +++ b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs @@ -1,26 +1,25 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Injects resolvable properties that do not already have a value. +/// +internal class UnsetPropertyInjection : PageInjectionBehavior { /// - /// Injects resolvable properties that do not already have a value. + /// Override to return a closure that injects properties into a target. /// - internal class UnsetPropertyInjection : PageInjectionBehavior + /// The context. + /// The injector. + protected override Func GetInjector(IComponentContext context) { - /// - /// Override to return a closure that injects properties into a target. - /// - /// The context. - /// The injector. - protected override Func GetInjector(IComponentContext context) + if (context == null) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - return context.InjectUnsetProperties; + throw new ArgumentNullException(nameof(context)); } + + return context.InjectUnsetProperties; } } diff --git a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs index f20bee8..3f7dd9e 100644 --- a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs @@ -1,29 +1,28 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web.Forms +namespace Autofac.Integration.Web.Forms; + +/// +/// Dependency injection module that will always inject any resolvable +/// properties. +/// +public class UnsetPropertyInjectionModule : DependencyInjectionModule { + private readonly IInjectionBehavior _injectUnsetProperties = new UnsetPropertyInjection(); + /// - /// Dependency injection module that will always inject any resolvable - /// properties. + /// Override to customize injection behavior based on HTTP Handler type. /// - public class UnsetPropertyInjectionModule : DependencyInjectionModule + /// Type of the handler. + /// The injection behavior. + protected override IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType) { - private readonly IInjectionBehavior _injectUnsetProperties = new UnsetPropertyInjection(); - - /// - /// Override to customize injection behavior based on HTTP Handler type. - /// - /// Type of the handler. - /// The injection behavior. - protected override IInjectionBehavior GetInjectionBehaviorForHandlerType(Type handlerType) + if (handlerType == null) { - if (handlerType == null) - { - throw new ArgumentNullException(nameof(handlerType)); - } - - return _injectUnsetProperties; + throw new ArgumentNullException(nameof(handlerType)); } + + return _injectUnsetProperties; } } diff --git a/src/Autofac.Integration.Web/IContainerProvider.cs b/src/Autofac.Integration.Web/IContainerProvider.cs index ff6b839..8bcb909 100644 --- a/src/Autofac.Integration.Web/IContainerProvider.cs +++ b/src/Autofac.Integration.Web/IContainerProvider.cs @@ -1,29 +1,28 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web +namespace Autofac.Integration.Web; + +/// +/// Provides global and per-request Autofac containers in an +/// ASP.NET application. +/// +public interface IContainerProvider { /// - /// Provides global and per-request Autofac containers in an - /// ASP.NET application. + /// Dispose of the current request's container, if it has been + /// instantiated. /// - public interface IContainerProvider - { - /// - /// Dispose of the current request's container, if it has been - /// instantiated. - /// - ValueTask EndRequestLifetime(); + ValueTask EndRequestLifetime(); - /// - /// Gets the global, application-wide container. - /// - IContainer ApplicationContainer { get; } + /// + /// Gets the global, application-wide container. + /// + IContainer ApplicationContainer { get; } - /// - /// Gets the lifetime used to manage components for processing the - /// current request. - /// - ILifetimeScope RequestLifetime { get; } - } + /// + /// Gets the lifetime used to manage components for processing the + /// current request. + /// + ILifetimeScope RequestLifetime { get; } } diff --git a/src/Autofac.Integration.Web/IContainerProviderAccessor.cs b/src/Autofac.Integration.Web/IContainerProviderAccessor.cs index 7333c31..63930ad 100644 --- a/src/Autofac.Integration.Web/IContainerProviderAccessor.cs +++ b/src/Autofac.Integration.Web/IContainerProviderAccessor.cs @@ -1,18 +1,17 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. -namespace Autofac.Integration.Web +namespace Autofac.Integration.Web; + +/// +/// Implemented on a type (i.e. HttpApplication) that maintains a container provider +/// for injecting dependencies into web requests. +/// +public interface IContainerProviderAccessor { /// - /// Implemented on a type (i.e. HttpApplication) that maintains a container provider - /// for injecting dependencies into web requests. + /// Gets the container provider. /// - public interface IContainerProviderAccessor - { - /// - /// Gets the container provider. - /// - /// The container provider. - IContainerProvider ContainerProvider { get; } - } + /// The container provider. + IContainerProvider ContainerProvider { get; } } diff --git a/src/Autofac.Integration.Web/RegistrationExtensions.cs b/src/Autofac.Integration.Web/RegistrationExtensions.cs index ca3d536..7e1f635 100644 --- a/src/Autofac.Integration.Web/RegistrationExtensions.cs +++ b/src/Autofac.Integration.Web/RegistrationExtensions.cs @@ -7,92 +7,91 @@ using Autofac.Core; using Autofac.Core.Resolving.Pipeline; -namespace Autofac.Integration.Web +namespace Autofac.Integration.Web; + +/// +/// Extends registration syntax for common web scenarios. +/// +public static class RegistrationExtensions { /// - /// Extends registration syntax for common web scenarios. + /// Share one instance of the component within the context of a single + /// HTTP request. /// - public static class RegistrationExtensions + /// Registration limit type. + /// Activator data type. + /// Registration style. + /// The registration to configure. + /// Additional tags applied for matching lifetime scopes. + /// A registration builder allowing further configuration of the component. + /// + /// Thrown if is . + /// + [Obsolete("Instead of using the web-forms-specific InstancePerHttpRequest, please switch to the InstancePerRequest shared registration extension from Autofac core.")] + public static IRegistrationBuilder + InstancePerHttpRequest( + this IRegistrationBuilder registration, params object[] lifetimeScopeTags) { - /// - /// Share one instance of the component within the context of a single - /// HTTP request. - /// - /// Registration limit type. - /// Activator data type. - /// Registration style. - /// The registration to configure. - /// Additional tags applied for matching lifetime scopes. - /// A registration builder allowing further configuration of the component. - /// - /// Thrown if is . - /// - [Obsolete("Instead of using the web-forms-specific InstancePerHttpRequest, please switch to the InstancePerRequest shared registration extension from Autofac core.")] - public static IRegistrationBuilder - InstancePerHttpRequest( - this IRegistrationBuilder registration, params object[] lifetimeScopeTags) - { - return registration.InstancePerRequest(lifetimeScopeTags); - } + return registration.InstancePerRequest(lifetimeScopeTags); + } - /// - /// Cache instances in the web session. This implies external ownership (disposal is not - /// available.) All dependencies must also have external ownership. - /// - /// - /// It is strongly recommended that components cached per-session do not take dependencies on - /// other services. - /// - /// Registration limit type. - /// Activator data type. - /// Registration style. - /// The registration to configure. - /// A registration builder allowing further configuration of the component. - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "It is the responsibility of the registry to dispose of registrations.")] - public static IRegistrationBuilder - CacheInSession( - this IRegistrationBuilder registration) - where TActivatorData : IConcreteActivatorData - where TSingleRegistrationStyle : SingleRegistrationStyle + /// + /// Cache instances in the web session. This implies external ownership (disposal is not + /// available.) All dependencies must also have external ownership. + /// + /// + /// It is strongly recommended that components cached per-session do not take dependencies on + /// other services. + /// + /// Registration limit type. + /// Activator data type. + /// Registration style. + /// The registration to configure. + /// A registration builder allowing further configuration of the component. + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "It is the responsibility of the registry to dispose of registrations.")] + public static IRegistrationBuilder + CacheInSession( + this IRegistrationBuilder registration) + where TActivatorData : IConcreteActivatorData + where TSingleRegistrationStyle : SingleRegistrationStyle + { + if (registration == null) { - if (registration == null) - { - throw new ArgumentNullException(nameof(registration)); - } + throw new ArgumentNullException(nameof(registration)); + } - var services = registration.RegistrationData.Services.ToArray(); - registration.RegistrationData.ClearServices(); + var services = registration.RegistrationData.Services.ToArray(); + registration.RegistrationData.ClearServices(); - return registration - .ExternallyOwned() - .OnRegistered(e => + return registration + .ExternallyOwned() + .OnRegistered(e => + { + foreach (var service in services) { - foreach (var service in services) - { - e.ComponentRegistryBuilder.Register(RegistrationBuilder - .ForDelegate((c, p) => + e.ComponentRegistryBuilder.Register(RegistrationBuilder + .ForDelegate((c, p) => + { + var session = HttpContext.Current.Session; + object result; + lock (session.SyncRoot) { - var session = HttpContext.Current.Session; - object result; - lock (session.SyncRoot) + result = session[e.ComponentRegistration.Id.ToString()]; + if (result == null) { - result = session[e.ComponentRegistration.Id.ToString()]; - if (result == null) - { - var resolveRequest = new ResolveRequest(service, new ServiceRegistration(ServicePipelines.DefaultServicePipeline, e.ComponentRegistration), p); - result = c.ResolveComponent(resolveRequest); - session[e.ComponentRegistration.Id.ToString()] = result; - } + var resolveRequest = new ResolveRequest(service, new ServiceRegistration(ServicePipelines.DefaultServicePipeline, e.ComponentRegistration), p); + result = c.ResolveComponent(resolveRequest); + session[e.ComponentRegistration.Id.ToString()] = result; } + } - return result; - }) - .As(service) - .InstancePerLifetimeScope() - .ExternallyOwned() - .CreateRegistration()); - } - }); - } + return result; + }) + .As(service) + .InstancePerLifetimeScope() + .ExternallyOwned() + .CreateRegistration()); + } + }); } } diff --git a/src/Autofac.Integration.Web/WebLifetime.cs b/src/Autofac.Integration.Web/WebLifetime.cs index ee4bb06..4acdc23 100644 --- a/src/Autofac.Integration.Web/WebLifetime.cs +++ b/src/Autofac.Integration.Web/WebLifetime.cs @@ -3,17 +3,16 @@ using Autofac.Core.Lifetime; -namespace Autofac.Integration.Web +namespace Autofac.Integration.Web; + +/// +/// Constants used to tag liftime scopes within standard Autofac web applications. +/// +public static class WebLifetime { /// - /// Constants used to tag liftime scopes within standard Autofac web applications. + /// Application root lifetime scope tag. Use instead. /// - public static class WebLifetime - { - /// - /// Application root lifetime scope tag. Use instead. - /// - [Obsolete("Use Autofac.Core.LifetimeScope.RootTag for application lifetime scope tagging.")] - public static readonly object Application = LifetimeScope.RootTag; - } + [Obsolete("Use Autofac.Core.LifetimeScope.RootTag for application lifetime scope tagging.")] + public static readonly object Application = LifetimeScope.RootTag; } diff --git a/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs b/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs index f35067a..34abab7 100644 --- a/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs +++ b/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs @@ -4,114 +4,113 @@ using System.Web; using Autofac.Integration.Web.Forms; -namespace Autofac.Integration.Web.Test.Forms +namespace Autofac.Integration.Web.Test.Forms; + +public class AttributedInjectionModuleFixture { - public class AttributedInjectionModuleFixture - { - private const string ContextSuppliedString = "ContextSuppliedString"; - private const string ExplicitlyProvidedString = "ExplicitlyProvidedString"; + private const string ContextSuppliedString = "ContextSuppliedString"; + private const string ExplicitlyProvidedString = "ExplicitlyProvidedString"; - private class HttpHandler : IHttpHandler + private class HttpHandler : IHttpHandler + { + public bool IsReusable { - public bool IsReusable - { - get { throw new NotImplementedException(); } - } - - public void ProcessRequest(HttpContext context) - { - throw new NotImplementedException(); - } + get { throw new NotImplementedException(); } } - [InjectProperties] - private class PropertyInjectedPage : HttpHandler + public void ProcessRequest(HttpContext context) { - public string Property { get; set; } + throw new NotImplementedException(); } + } - [InjectUnsetProperties] - private class UnsetPropertyInjectedPage : HttpHandler - { - public string Property { get; set; } - } + [InjectProperties] + private class PropertyInjectedPage : HttpHandler + { + public string Property { get; set; } + } - private class NonInjectedPage : HttpHandler - { - public string Property { get; set; } - } + [InjectUnsetProperties] + private class UnsetPropertyInjectedPage : HttpHandler + { + public string Property { get; set; } + } - [Fact] - public void PropertyInjected() - { - var context = CreateContext(); - var page = new PropertyInjectedPage(); - var target = new AttributedInjectionModule(); - var injector = target.GetInjectionBehavior(page); - Assert.NotNull(injector); - injector.InjectDependencies(context, page); - Assert.Equal(ContextSuppliedString, page.Property); - } + private class NonInjectedPage : HttpHandler + { + public string Property { get; set; } + } - [Fact] - public void PropertyInjectedValueSet() - { - var context = CreateContext(); - var page = new PropertyInjectedPage - { - Property = ExplicitlyProvidedString, - }; - var target = new AttributedInjectionModule(); - var injector = target.GetInjectionBehavior(page); - Assert.NotNull(injector); - injector.InjectDependencies(context, page); - Assert.Equal(ContextSuppliedString, page.Property); - } + [Fact] + public void PropertyInjected() + { + var context = CreateContext(); + var page = new PropertyInjectedPage(); + var target = new AttributedInjectionModule(); + var injector = target.GetInjectionBehavior(page); + Assert.NotNull(injector); + injector.InjectDependencies(context, page); + Assert.Equal(ContextSuppliedString, page.Property); + } - [Fact] - public void UnsetPropertyInjected() + [Fact] + public void PropertyInjectedValueSet() + { + var context = CreateContext(); + var page = new PropertyInjectedPage { - var context = CreateContext(); - var page = new UnsetPropertyInjectedPage(); - var target = new AttributedInjectionModule(); - var injector = target.GetInjectionBehavior(page); - Assert.NotNull(injector); - injector.InjectDependencies(context, page); - Assert.Equal(ContextSuppliedString, page.Property); - } + Property = ExplicitlyProvidedString, + }; + var target = new AttributedInjectionModule(); + var injector = target.GetInjectionBehavior(page); + Assert.NotNull(injector); + injector.InjectDependencies(context, page); + Assert.Equal(ContextSuppliedString, page.Property); + } - [Fact] - public void PropertyNotInjectedWhenValueSet() - { - var context = CreateContext(); - var page = new UnsetPropertyInjectedPage - { - Property = ExplicitlyProvidedString, - }; - var target = new AttributedInjectionModule(); - var injector = target.GetInjectionBehavior(page); - Assert.NotNull(injector); - injector.InjectDependencies(context, page); - Assert.Equal(ExplicitlyProvidedString, page.Property); - } + [Fact] + public void UnsetPropertyInjected() + { + var context = CreateContext(); + var page = new UnsetPropertyInjectedPage(); + var target = new AttributedInjectionModule(); + var injector = target.GetInjectionBehavior(page); + Assert.NotNull(injector); + injector.InjectDependencies(context, page); + Assert.Equal(ContextSuppliedString, page.Property); + } - [Fact] - public void PropertyNotInjected() + [Fact] + public void PropertyNotInjectedWhenValueSet() + { + var context = CreateContext(); + var page = new UnsetPropertyInjectedPage { - var context = CreateContext(); - var page = new NonInjectedPage(); - var target = new AttributedInjectionModule(); - var injector = target.GetInjectionBehavior(page); - Assert.NotNull(injector); - injector.InjectDependencies(context, page); - Assert.Null(page.Property); - } + Property = ExplicitlyProvidedString, + }; + var target = new AttributedInjectionModule(); + var injector = target.GetInjectionBehavior(page); + Assert.NotNull(injector); + injector.InjectDependencies(context, page); + Assert.Equal(ExplicitlyProvidedString, page.Property); + } - private IComponentContext CreateContext() - { - var cb = new ContainerBuilder(); - cb.RegisterInstance(ContextSuppliedString); - return cb.Build(); - } + [Fact] + public void PropertyNotInjected() + { + var context = CreateContext(); + var page = new NonInjectedPage(); + var target = new AttributedInjectionModule(); + var injector = target.GetInjectionBehavior(page); + Assert.NotNull(injector); + injector.InjectDependencies(context, page); + Assert.Null(page.Property); + } + + private IComponentContext CreateContext() + { + var cb = new ContainerBuilder(); + cb.RegisterInstance(ContextSuppliedString); + return cb.Build(); } } diff --git a/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs b/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs index e24298a..fd855e2 100644 --- a/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs +++ b/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs @@ -5,77 +5,76 @@ using System.Web; using System.Web.SessionState; -namespace Autofac.Integration.Web.Test +namespace Autofac.Integration.Web.Test; + +public class RegistrationExtensionsFixture { - public class RegistrationExtensionsFixture + private interface ICounter { - private interface ICounter - { - } + } - private class Counter : ICounter - { - public static int Constructed { get; private set; } + private class Counter : ICounter + { + public static int Constructed { get; private set; } - public Counter() - { - Constructed++; - } + public Counter() + { + Constructed++; } + } - public static HttpContext FakeHttpContext() - { - // source: https://stackoverflow.com/a/10126711/6887257 - var httpRequest = new HttpRequest("", "http://stackoverflow/", ""); - var stringWriter = new StringWriter(); - var httpResponse = new HttpResponse(stringWriter); - var httpContext = new HttpContext(httpRequest, httpResponse); + public static HttpContext FakeHttpContext() + { + // source: https://stackoverflow.com/a/10126711/6887257 + var httpRequest = new HttpRequest("", "http://stackoverflow/", ""); + var stringWriter = new StringWriter(); + var httpResponse = new HttpResponse(stringWriter); + var httpContext = new HttpContext(httpRequest, httpResponse); - var sessionContainer = new HttpSessionStateContainer( - "id", - new SessionStateItemCollection(), - new HttpStaticObjectsCollection(), - 10, - true, - HttpCookieMode.AutoDetect, - SessionStateMode.InProc, - false); + var sessionContainer = new HttpSessionStateContainer( + "id", + new SessionStateItemCollection(), + new HttpStaticObjectsCollection(), + 10, + true, + HttpCookieMode.AutoDetect, + SessionStateMode.InProc, + false); - httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( - BindingFlags.NonPublic | BindingFlags.Instance, - null, - CallingConventions.Standard, - new[] { typeof(HttpSessionStateContainer) }, - null) - .Invoke(new object[] { sessionContainer }); + httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( + BindingFlags.NonPublic | BindingFlags.Instance, + null, + CallingConventions.Standard, + new[] { typeof(HttpSessionStateContainer) }, + null) + .Invoke(new object[] { sessionContainer }); - return httpContext; - } + return httpContext; + } - [Fact] - public void VerifyInstanceLifetimeIsSession() - { - var builder = new ContainerBuilder(); - builder.RegisterType().AsSelf().As().CacheInSession(); - var container = builder.Build(); + [Fact] + public void VerifyInstanceLifetimeIsSession() + { + var builder = new ContainerBuilder(); + builder.RegisterType().AsSelf().As().CacheInSession(); + var container = builder.Build(); - HttpContext.Current = FakeHttpContext(); - using (var scope = container.BeginLifetimeScope()) - { - var iCounter = scope.Resolve(); - Assert.IsType(iCounter); - Assert.Equal(1, Counter.Constructed); + HttpContext.Current = FakeHttpContext(); + using (var scope = container.BeginLifetimeScope()) + { + var iCounter = scope.Resolve(); + Assert.IsType(iCounter); + Assert.Equal(1, Counter.Constructed); - scope.Resolve(); - Assert.Equal(1, Counter.Constructed); - } + scope.Resolve(); + Assert.Equal(1, Counter.Constructed); + } - HttpContext.Current = FakeHttpContext(); - using (var scope = container.BeginLifetimeScope()) - { - scope.Resolve(); - Assert.Equal(2, Counter.Constructed); - } + HttpContext.Current = FakeHttpContext(); + using (var scope = container.BeginLifetimeScope()) + { + scope.Resolve(); + Assert.Equal(2, Counter.Constructed); } } } From 4314d1397f5823d47a6df08e65d7d51b84c0b407 Mon Sep 17 00:00:00 2001 From: Travis Illig Date: Thu, 21 Jul 2022 14:15:43 -0700 Subject: [PATCH 5/5] README formatted for packaging. --- README.md | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f6a9b24..7b4d966 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,81 @@ ASP.NET web forms integration for [Autofac](https://autofac.org). -[![Build status](https://ci.appveyor.com/api/projects/status/m440xdhvmm15iiw0?svg=true)](https://ci.appveyor.com/project/Autofac/autofac-web) [![Open in Visual Studio Code](https://open.vscode.dev/badges/open-in-vscode.svg)](https://open.vscode.dev/autofac/Autofac.Web) +[![Build status](https://ci.appveyor.com/api/projects/status/m440xdhvmm15iiw0?svg=true)](https://ci.appveyor.com/project/Autofac/autofac-web) -Please file issues and pull requests for this package in this repository rather than in the Autofac core repo. +Please file issues and pull requests for this package [in this repository](https://github.com/autofac/Autofac.Web/issues) rather than in the Autofac core repo. - [Documentation](https://autofac.readthedocs.io/en/latest/integration/webforms.html) - [NuGet](https://www.nuget.org/packages/Autofac.Web/) - [Contributing](https://autofac.readthedocs.io/en/latest/contributors.html) +- [Open in Visual Studio Code](https://open.vscode.dev/autofac/Autofac.Web) + +## Quick Start + +To get Autofac integrated with web forms you need to reference the web forms integration NuGet package, add the modules to `web.config`, and implement `IContainerProviderAccessor` on your `Global` application class. + +Add the modules to `web.config`: + +```xml + + + + + + + + + + + + + + + + +``` + +Implement `IContainerProviderAccessor`: + +```c# +public class Global : HttpApplication, IContainerProviderAccessor +{ + // Provider that holds the application container. + static IContainerProvider _containerProvider; + + // Instance property that will be used by Autofac HttpModules + // to resolve and inject dependencies. + public IContainerProvider ContainerProvider + { + get { return _containerProvider; } + } + + protected void Application_Start(object sender, EventArgs e) + { + // Build up your application container and register your dependencies. + var builder = new ContainerBuilder(); + builder.RegisterType(); + // ... continue registering dependencies... + + // Once you're done registering things, set the container + // provider up with your registrations. + _containerProvider = new ContainerProvider(builder.Build()); + } +} +``` + +[Check out the documentation](https://autofac.readthedocs.io/en/latest/integration/webforms.html) for more usage details. + +## Get Help + +**Need help with Autofac?** We have [a documentation site](https://autofac.readthedocs.io/) as well as [API documentation](https://autofac.org/apidoc/). We're ready to answer your questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/autofac) or check out the [discussion forum](https://groups.google.com/forum/#forum/autofac).