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/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). 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..33a01cc 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 @@ -81,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..768b1de 100644 --- a/src/Autofac.Integration.Web/ContainerDisposalModule.cs +++ b/src/Autofac.Integration.Web/ContainerDisposalModule.cs @@ -1,90 +1,74 @@ -// 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; +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. - /// - 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 5fb5497..0ba3dc2 100644 --- a/src/Autofac.Integration.Web/ContainerProvider.cs +++ b/src/Autofac.Integration.Web/ContainerProvider.cs @@ -1,111 +1,89 @@ -// 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; 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 - /// customised 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 fed731b..19008d9 100644 --- a/src/Autofac.Integration.Web/ContainerProviderContainer.cs +++ b/src/Autofac.Integration.Web/ContainerProviderContainer.cs @@ -1,213 +1,188 @@ -// 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. - -using System; -using System.Collections.Generic; +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Threading.Tasks; using Autofac.Builder; using Autofac.Core; using Autofac.Core.Lifetime; 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 registations 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 registations 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. - /// - [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() - { - } + /// + /// 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() - { - return default; - } + /// + /// Performs application-defined tasks associated with freeing, releasing, or + /// resetting unmanaged resources asynchronously. + /// + 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..060cbfd 100644 --- a/src/Autofac.Integration.Web/Forms/AttributedInjection.cs +++ b/src/Autofac.Integration.Web/Forms/AttributedInjection.cs @@ -1,65 +1,42 @@ -// 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; +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) - { - return context.InjectProperties(target); - } - else if (targetType.GetCustomAttributes(typeof(InjectUnsetPropertiesAttribute), true).Length > 0) - { - return context.InjectUnsetProperties(target); - } - else - { - return target; - } - }; + 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; + } + }; } } diff --git a/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs b/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs index 5c1e63e..6232365 100644 --- a/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/AttributedInjectionModule.cs @@ -1,52 +1,29 @@ -// 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; +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 IInjectionBehavior _attributedInjection = new AttributedInjection(); - - /// - /// Override to customise 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 2fe0e6e..6706dbb 100644 --- a/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/DependencyInjectionAttribute.cs @@ -1,37 +1,12 @@ -// 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; +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 9701e5b..f1178ef 100644 --- a/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/DependencyInjectionModule.cs @@ -1,123 +1,106 @@ -// 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; -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; + /// - /// Base for classes that inject dependencies into HTTP Handlers. + /// Disposes of the resources (other than memory) used by the module that implements . /// - public abstract class DependencyInjectionModule : IHttpModule + public void Dispose() { - private IContainerProviderAccessor _containerProviderAccessor; - private HttpApplication _httpApplication; + } - /// - /// 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) + { + _httpApplication = context ?? throw new ArgumentNullException(nameof(context)); + _containerProviderAccessor = context as IContainerProviderAccessor; - /// - /// 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 (_containerProviderAccessor == null) { - _httpApplication = context ?? throw new ArgumentNullException(nameof(context)); - _containerProviderAccessor = context as IContainerProviderAccessor; - - if (_containerProviderAccessor == null) - throw new InvalidOperationException(DependencyInjectionModuleResources.ApplicationMustImplementAccessor); - - context.PreRequestHandlerExecute += OnPreRequestHandlerExecute; + throw new InvalidOperationException(DependencyInjectionModuleResources.ApplicationMustImplementAccessor); } - /// - /// 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) + context.PreRequestHandlerExecute += OnPreRequestHandlerExecute; + } + + /// + /// 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 handler = _httpApplication.Context.CurrentHandler; - if (handler != null) + var injectionBehavior = GetInjectionBehavior(handler); + var cp = _containerProviderAccessor?.ContainerProvider; + if (cp == null) { - var injectionBehavior = GetInjectionBehavior(handler); - var cp = _containerProviderAccessor.ContainerProvider; - if (cp == null) - throw new InvalidOperationException(ContainerDisposalModuleResources.ContainerProviderNull); - injectionBehavior.InjectDependencies(cp.RequestLifetime, handler); + throw new InvalidOperationException(ContainerDisposalModuleResources.ContainerProviderNull); } + + injectionBehavior.InjectDependencies(cp.RequestLifetime, 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) + /// + /// 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) { - if (handler == null) - throw new ArgumentNullException(nameof(handler)); + throw new ArgumentNullException(nameof(handler)); + } - if (handler is DefaultHttpHandler) - { - return NoInjection; - } - else - { - var handlerType = handler.GetType(); - return GetInjectionBehaviorForHandlerType(handlerType); - } + if (handler is DefaultHttpHandler) + { + 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 1be16c1..ca73c35 100644 --- a/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs +++ b/src/Autofac.Integration.Web/Forms/IInjectionBehavior.cs @@ -1,40 +1,17 @@ -// 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 +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 71612b0..bad0b67 100644 --- a/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/InjectPropertiesAttribute.cs @@ -1,37 +1,12 @@ -// 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; +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 d99aef8..5d778b5 100644 --- a/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs +++ b/src/Autofac.Integration.Web/Forms/InjectUnsetPropertiesAttribute.cs @@ -1,38 +1,13 @@ -// 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; +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 5e59165..d66dfa5 100644 --- a/src/Autofac.Integration.Web/Forms/NoInjection.cs +++ b/src/Autofac.Integration.Web/Forms/NoInjection.cs @@ -1,42 +1,19 @@ -// 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 +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 f831765..eda01cc 100644 --- a/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs +++ b/src/Autofac.Integration.Web/Forms/PageInjectionBehavior.cs @@ -1,99 +1,94 @@ -// 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. - -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.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); + var injector = GetInjector(context); - DoInjection(injector, target); - } + DoInjection(injector, target); + } - /// - /// 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) + /// + /// 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 (injector == null) { - if (injector == null) - throw new ArgumentNullException(nameof(injector)); + throw new ArgumentNullException(nameof(injector)); + } - if (target == null) - 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) + private static void InjectUserControls(Func injector, Control parent) + { + if (injector == null) { - if (injector == null) - throw new ArgumentNullException(nameof(injector)); + throw new ArgumentNullException(nameof(injector)); + } - if (parent == null) - throw new ArgumentNullException(nameof(parent)); + if (parent == null) + { + throw new ArgumentNullException(nameof(parent)); + } - if (parent.Controls == null) - return; + if (parent.Controls == null) + { + return; + } - foreach (Control control in parent.Controls) + foreach (Control control in parent.Controls) + { + if (control is UserControl uc) { - if (control is UserControl uc) - injector(uc); - InjectUserControls(injector, control); + 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..58d9fdf 100644 --- a/src/Autofac.Integration.Web/Forms/PropertyInjection.cs +++ b/src/Autofac.Integration.Web/Forms/PropertyInjection.cs @@ -1,48 +1,25 @@ -// 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; +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 614efeb..7fec831 100644 --- a/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/PropertyInjectionModule.cs @@ -1,51 +1,28 @@ -// 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; +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 IInjectionBehavior _injectProperties = new PropertyInjection(); - - /// - /// Override to customise 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 b01f66c..70608c0 100644 --- a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs +++ b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjection.cs @@ -1,48 +1,25 @@ -// 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; +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 78ce586..3f7dd9e 100644 --- a/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs +++ b/src/Autofac.Integration.Web/Forms/UnsetPropertyInjectionModule.cs @@ -1,51 +1,28 @@ -// 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; +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 IInjectionBehavior _injectUnsetProperties = new UnsetPropertyInjection(); - - /// - /// Override to customise 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 66c1a67..8bcb909 100644 --- a/src/Autofac.Integration.Web/IContainerProvider.cs +++ b/src/Autofac.Integration.Web/IContainerProvider.cs @@ -1,52 +1,28 @@ -// 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; +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 b5d3956..63930ad 100644 --- a/src/Autofac.Integration.Web/IContainerProviderAccessor.cs +++ b/src/Autofac.Integration.Web/IContainerProviderAccessor.cs @@ -1,39 +1,17 @@ -// 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 +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/Properties/AssemblyInfo.cs b/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs index ca8468d..2ee8058 100644 --- a/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs +++ b/src/Autofac.Integration.Web/Properties/AssemblyInfo.cs @@ -1,6 +1,6 @@ -using System; -using System.Reflection; -using System.Resources; +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + 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 7201005..7e1f635 100644 --- a/src/Autofac.Integration.Web/RegistrationExtensions.cs +++ b/src/Autofac.Integration.Web/RegistrationExtensions.cs @@ -1,119 +1,97 @@ -// 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; -using System.Linq; using System.Web; using Autofac.Builder; 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 a39942a..4acdc23 100644 --- a/src/Autofac.Integration.Web/WebLifetime.cs +++ b/src/Autofac.Integration.Web/WebLifetime.cs @@ -1,41 +1,18 @@ -// 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 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/Autofac.Integration.Web.Test.csproj b/test/Autofac.Integration.Web.Test/Autofac.Integration.Web.Test.csproj index dff2d2b..0cc0677 100644 --- a/test/Autofac.Integration.Web.Test/Autofac.Integration.Web.Test.csproj +++ b/test/Autofac.Integration.Web.Test/Autofac.Integration.Web.Test.csproj @@ -1,31 +1,44 @@  - 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 + + + + + + + - \ 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..34abab7 100644 --- a/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs +++ b/test/Autofac.Integration.Web.Test/Forms/AttributedInjectionModuleFixture.cs @@ -1,116 +1,116 @@ -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.Web; using Autofac.Integration.Web.Forms; -using Xunit; -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(); } -} \ 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..fd855e2 100644 --- a/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs +++ b/test/Autofac.Integration.Web.Test/RegistrationExtensionsFixture.cs @@ -1,80 +1,80 @@ -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.Reflection; using System.Web; using System.Web.SessionState; -using Xunit; -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); } } }