Repository: autofac/Autofac.Extensions.DependencyInjection
Branch: develop
Commit: 303d9a8194cf
Files: 115
Total size: 249.0 KB
Directory structure:
gitextract_omufirln/
├── .editorconfig
├── .gitattributes
├── .github/
│ └── workflows/
│ ├── build.yml
│ ├── ci.yml
│ ├── dotnet-format.yml
│ ├── pre-commit.yml
│ └── publish.yml
├── .gitignore
├── .markdownlint.json
├── .pre-commit-config.yaml
├── .vscode/
│ ├── extensions.json
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── Autofac.Extensions.DependencyInjection.sln
├── Autofac.Extensions.DependencyInjection.sln.DotSettings
├── Autofac.snk
├── Directory.Build.props
├── LICENSE
├── README.md
├── bench/
│ └── Autofac.Extensions.DependencyInjection.Bench/
│ ├── Autofac.Extensions.DependencyInjection.Bench.csproj
│ ├── AutofacWebApplicationFactory.cs
│ ├── BenchWebApplicationFactory.cs
│ ├── BenchmarkConfig.cs
│ ├── Benchmarks.cs
│ ├── DefaultWebApplicationFactory.cs
│ ├── Harness.cs
│ ├── KeyedResolutionBenchmark.cs
│ ├── Program.cs
│ ├── Properties/
│ │ └── AssemblyInfo.cs
│ ├── RequestBenchmark.cs
│ ├── SampleApp/
│ │ ├── Controllers/
│ │ │ └── ValuesController.cs
│ │ ├── DefaultStartup.cs
│ │ ├── Program.cs
│ │ └── Services.cs
│ └── xunit.runner.json
├── build/
│ ├── Coverage.runsettings
│ ├── Source.ruleset
│ ├── Test.ruleset
│ └── stylecop.json
├── codecov.yml
├── default.proj
├── global.json
├── src/
│ └── Autofac.Extensions.DependencyInjection/
│ ├── Autofac.Extensions.DependencyInjection.csproj
│ ├── AutofacChildLifetimeScopeConfigurationAdapter.cs
│ ├── AutofacChildLifetimeScopeServiceProviderFactory.cs
│ ├── AutofacRegistration.cs
│ ├── AutofacServiceProvider.cs
│ ├── AutofacServiceProviderFactory.cs
│ ├── AutofacServiceScope.cs
│ ├── AutofacServiceScopeFactory.cs
│ ├── FromKeyedServicesAttributeExtensions.cs
│ ├── FromKeyedServicesUsageCache.cs
│ ├── KeyTypeConversionException.cs
│ ├── KeyTypeConversionExceptionResources.resx
│ ├── KeyTypeManipulation.cs
│ ├── KeyTypeManipulationResources.resx
│ ├── KeyedServiceMiddleware.cs
│ ├── Polyfills/
│ │ └── NotNullWhenAttribute.cs
│ ├── Properties/
│ │ └── AssemblyInfo.cs
│ ├── ServiceCollectionExtensions.cs
│ ├── ServiceDescriptorExtensions.cs
│ ├── ServiceProviderExtensions.cs
│ ├── ServiceProviderExtensionsResources.resx
│ └── TypeExtensions.cs
└── test/
├── Autofac.Extensions.DependencyInjection.Integration.Test/
│ ├── Autofac.Extensions.DependencyInjection.Integration.Test.csproj
│ ├── IntegrationTests.cs
│ └── Properties/
│ └── AssemblyInfo.cs
├── Autofac.Extensions.DependencyInjection.Test/
│ ├── Assertions.cs
│ ├── Autofac.Extensions.DependencyInjection.Test.csproj
│ ├── AutofacChildLifetimeScopeConfigurationAdapterTests.cs
│ ├── AutofacChildLifetimeScopeServiceProviderFactoryTests.cs
│ ├── AutofacRegistrationTests.cs
│ ├── AutofacServiceProviderFactoryTests.cs
│ ├── AutofacServiceProviderTests.cs
│ ├── FromKeyedServicesAttributeExtensionsTests.cs
│ ├── FromKeyedServicesUsageCacheTests.cs
│ ├── KeyTypeManipulationFixture.cs
│ ├── KeyedServiceTests.cs
│ ├── Properties/
│ │ └── AssemblyInfo.cs
│ ├── ServiceCollectionExtensionsTests.cs
│ ├── ServiceProviderExtensionsTests.cs
│ ├── Specification/
│ │ ├── AssumedBehaviorTests.cs
│ │ ├── BuilderAssumedBehaviorTests.cs
│ │ ├── BuilderKeyedSpecificationTests.cs
│ │ ├── BuilderSpecificationTests.cs
│ │ ├── ChildScopeFactoryAssumedBehaviorTests.cs
│ │ ├── ChildScopeFactoryKeyedSpecificationTests.cs
│ │ ├── ChildScopeFactorySpecificationTests.cs
│ │ ├── FactoryAssumedBehaviorTests.cs
│ │ ├── FactoryKeyedSpecificationTests.cs
│ │ ├── FactorySpecificationTests.cs
│ │ └── MicrosoftAssumedBehaviorTests.cs
│ ├── TestCulture.cs
│ └── TypeExtensionsTests.cs
├── Integration.Net10/
│ ├── Controllers/
│ │ └── DateController.cs
│ ├── DateProvider.cs
│ ├── IDateProvider.cs
│ ├── Integration.Net10.csproj
│ ├── Program.cs
│ ├── Properties/
│ │ ├── AssemblyInfo.cs
│ │ └── launchSettings.json
│ ├── Startup.cs
│ ├── appsettings.Development.json
│ └── appsettings.json
└── Integration.Net8/
├── Controllers/
│ └── DateController.cs
├── DateProvider.cs
├── IDateProvider.cs
├── Integration.Net8.csproj
├── Program.cs
├── Properties/
│ ├── AssemblyInfo.cs
│ └── launchSettings.json
├── Startup.cs
├── appsettings.Development.json
└── appsettings.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
; 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,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:warning
; 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]
end_of_line = crlf
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
# YAML - match standard YAML like Kubernetes and GitHub Actions
[*.{yaml,yml}]
indent_size = 2
================================================
FILE: .gitattributes
================================================
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
*.jpg binary
*.png binary
*.gif binary
*.cs text=auto diff=csharp
*.vb text=auto
*.resx text=auto
*.c text=auto
*.cpp text=auto
*.cxx text=auto
*.h text=auto
*.hxx text=auto
*.py text=auto
*.rb text=auto
*.java text=auto
*.html text=auto
*.htm text=auto
*.css text=auto
*.scss text=auto
*.sass text=auto
*.less text=auto
*.js text=auto
*.lisp text=auto
*.clj text=auto
*.sql text=auto
*.php text=auto
*.lua text=auto
*.m text=auto
*.asm text=auto
*.erl text=auto
*.fs text=auto
*.fsx text=auto
*.hs text=auto
*.csproj text=auto
*.vbproj text=auto
*.fsproj text=auto
*.dbproj text=auto
*.sln text=auto eol=crlf
================================================
FILE: .github/workflows/build.yml
================================================
name: Build and Test
on:
workflow_call:
secrets:
CODECOV_TOKEN:
description: Token for uploading code coverage metrics to CodeCov.io.
required: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup .NET
uses: actions/setup-dotnet@v5
with:
dotnet-version: |
8.0.x
10.0.x
- name: Build and test
run: dotnet msbuild ./default.proj
- name: Upload coverage
uses: codecov/codecov-action@v5
with:
fail_ci_if_error: true
files: artifacts/logs/*/coverage.cobertura.xml
token: ${{ secrets.CODECOV_TOKEN }}
- name: Upload package artifacts
uses: actions/upload-artifact@v7
with:
name: packages
path: |
artifacts/packages/*.nupkg
artifacts/packages/*.snupkg
================================================
FILE: .github/workflows/ci.yml
================================================
name: Continuous Integration
on:
pull_request:
branches:
- develop
- master
push:
branches:
- develop
- master
- feature/*
tags:
- v[0-9]+.[0-9]+.[0-9]+
# If multiple pushes happen quickly in succession, cancel the running build and
# start a new one.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
# Linting
dotnet-format:
uses: ./.github/workflows/dotnet-format.yml
pre-commit:
uses: ./.github/workflows/pre-commit.yml
# Build and test
build:
uses: ./.github/workflows/build.yml
secrets:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
# Publish beta and release packages.
publish:
uses: ./.github/workflows/publish.yml
needs:
- build
- dotnet-format
- pre-commit
if: ${{ github.ref == 'refs/heads/develop' || startsWith(github.ref, 'refs/tags/v') }}
secrets:
NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
================================================
FILE: .github/workflows/dotnet-format.yml
================================================
name: dotnet format
on:
workflow_call:
jobs:
dotnet-format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Setup .NET 10
uses: actions/setup-dotnet@v5
with:
dotnet-version: 10.0.x
- name: dotnet format
run: dotnet format Autofac.Extensions.DependencyInjection.sln --verify-no-changes
================================================
FILE: .github/workflows/pre-commit.yml
================================================
name: pre-commit
on:
workflow_call:
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: 3.x
- uses: pre-commit/action@v3.0.1
================================================
FILE: .github/workflows/publish.yml
================================================
name: Publish
on:
workflow_call:
secrets:
NUGET_API_KEY:
description: Token for publishing packages to NuGet.
required: true
jobs:
publish:
runs-on: ubuntu-latest
steps:
- name: Setup .NET
uses: actions/setup-dotnet@v5
with:
dotnet-version: 10.0.x
- name: Download package artifacts
uses: actions/download-artifact@v8
with:
name: packages
path: artifacts/packages
- name: Publish to GitHub Packages
run: |
dotnet nuget add source --username USERNAME --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name github "https://nuget.pkg.github.com/autofac/index.json"
dotnet nuget push ./artifacts/packages/*.nupkg --skip-duplicate --source github --api-key ${{ secrets.GITHUB_TOKEN }}
dotnet nuget push ./artifacts/packages/*.snupkg --skip-duplicate --source github --api-key ${{ secrets.GITHUB_TOKEN }}
- name: Publish to NuGet
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
run: |
dotnet nuget push ./artifacts/packages/*.nupkg --skip-duplicate --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
================================================
FILE: .gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# Project specific files
artifacts/
BenchmarkDotNet.Artifacts/
# User-specific files
*.suo
*.user
*.sln.docstates
*.ide
Index.dat
Storage.dat
# Build results
[Dd]ebug/
[Rr]elease/
x64/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.dotnet/
.vs/
.cr/
# Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
!packages/*/build/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
*.TestResults.xml
results/
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.log
*.scc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.pubxml
# NuGet Packages Directory
packages/
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
!stylecop.json
~$*
*~
*.dbmdl
*.pfx
*.publishsettings
node_modules/
bower_components/
wwwroot/
project.lock.json
*.Designer.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
App_Data/*.mdf
App_Data/*.ldf
# =========================
# Windows detritus
# =========================
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Mac crap
.DS_Store
# JetBrains Rider
.idea
================================================
FILE: .markdownlint.json
================================================
{
"MD013": false
}
================================================
FILE: .pre-commit-config.yaml
================================================
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: "3e8a8703264a2f4a69428a0aa4dcb512790b2c8c" # frozen: v6.0.0
hooks:
- id: check-json
- id: check-yaml
- id: check-merge-conflict
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/igorshubovych/markdownlint-cli
rev: "76b3d32d3f4b965e1d6425253c59407420ae2c43" # frozen: v0.47.0
hooks:
- id: markdownlint
args:
- --fix
- repo: https://github.com/tillig/json-sort-cli
rev: "009ab2ab49e1f2fa9d6b9dfc31009ceeca055204" # frozen: v3.0.0
hooks:
- id: json-sort
args:
- --autofix
================================================
FILE: .vscode/extensions.json
================================================
{
"recommendations": [
"davidanson.vscode-markdownlint",
"editorconfig.editorconfig",
"ms-dotnettools.csdevkit",
"travisillig.vscode-json-stable-stringify"
]
}
================================================
FILE: .vscode/launch.json
================================================
{
"configurations": [
{
"args": [
],
"cwd": "${workspaceFolder}/test/Integration.Net8",
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"name": "Launch .NET 8 Integration Site",
"preLaunchTask": "build",
"program": "${workspaceFolder}/test/Integration.Net8/bin/Debug/net8.0/Integration.Net8.dll",
"request": "launch",
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)",
"uriFormat": "%s/date"
},
"stopAtEntry": false,
"type": "coreclr"
},
{
"args": [
],
"cwd": "${workspaceFolder}/test/Integration.Net10",
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"name": "Launch .NET 10 Integration Site",
"preLaunchTask": "build",
"program": "${workspaceFolder}/test/Integration.Net10/bin/Debug/net10.0/Integration.Net10.dll",
"request": "launch",
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)",
"uriFormat": "%s/date"
},
"stopAtEntry": false,
"type": "coreclr"
}
],
"version": "0.2.0"
}
================================================
FILE: .vscode/settings.json
================================================
{
"cSpell.words": [
"autofac",
"cref",
"diagnoser",
"diagnosers",
"inheritdoc",
"langword",
"paramref",
"seealso",
"typeparam",
"unmanaged",
"xunit"
],
"coverage-gutters.coverageBaseDir": "artifacts/logs",
"coverage-gutters.coverageFileNames": [
"**/coverage.cobertura.xml"
],
"dotnet.defaultSolution": "Autofac.Extensions.DependencyInjection.sln",
"dotnet.unitTestDebuggingOptions": {
"enableStepFiltering": false,
"justMyCode": false,
"requireExactSource": false,
"sourceLinkOptions": {
"*": {
"enabled": true
}
},
"suppressJITOptimizations": true,
"symbolOptions": {
"searchNuGetOrgSymbolServer": true
}
},
"explorer.fileNesting.enabled": true,
"explorer.fileNesting.patterns": {
"*.resx": "$(capture).*.resx, $(capture).designer.cs, $(capture).designer.vb"
},
"files.watcherExclude": {
"**/target": true
}
}
================================================
FILE: .vscode/tasks.json
================================================
{
"linux": {
"options": {
"shell": {
"args": [
"-NoProfile",
"-Command"
],
"executable": "pwsh"
}
}
},
"osx": {
"options": {
"shell": {
"args": [
"-NoProfile",
"-Command"
],
"executable": "/usr/local/bin/pwsh"
}
}
},
"tasks": [
{
"command": "If (Test-Path ${workspaceFolder}/artifacts/logs) { Remove-Item ${workspaceFolder}/artifacts/logs -Recurse -Force }; New-Item -Path ${workspaceFolder}/artifacts/logs -ItemType Directory -Force | Out-Null",
"label": "create log directory",
"type": "shell"
},
{
"args": [
"build",
"${workspaceFolder}/Autofac.Extensions.DependencyInjection.sln",
"--tl:off",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"command": "dotnet",
"group": {
"isDefault": true,
"kind": "build"
},
"label": "build",
"problemMatcher": "$msCompile",
"type": "shell"
},
{
"args": [
"test",
"${workspaceFolder}/Autofac.Extensions.DependencyInjection.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary",
"--results-directory",
"artifacts/logs",
"--logger:trx",
"--collect:XPlat Code Coverage",
"--settings:build/Coverage.runsettings",
"--filter",
"FullyQualifiedName!~Bench"
],
"command": "dotnet",
"dependsOn": [
"create log directory"
],
"group": {
"isDefault": true,
"kind": "test"
},
"label": "test",
"problemMatcher": "$msCompile",
"type": "process"
}
],
"version": "2.0.0",
"windows": {
"options": {
"shell": {
"args": [
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-Command"
],
"executable": "pwsh.exe"
}
}
}
}
================================================
FILE: Autofac.Extensions.DependencyInjection.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29201.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5A54DF18-E3F3-4929-876D-00650A15763E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{DEA4A8C6-DE56-4359-A87C-472FB34132E7}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{6B324E70-6C86-4E09-B150-CAE9DD2BADCC}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
global.json = global.json
codecov.yml = codecov.yml
default.proj = default.proj
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Autofac.Extensions.DependencyInjection", "src\Autofac.Extensions.DependencyInjection\Autofac.Extensions.DependencyInjection.csproj", "{513C7F7A-A758-4D48-94F4-891A00F63DA1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Autofac.Extensions.DependencyInjection.Test", "test\Autofac.Extensions.DependencyInjection.Test\Autofac.Extensions.DependencyInjection.Test.csproj", "{911AA52A-4E68-41C5-AB24-D1618AFDF753}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "bench", "bench", "{C39BE99E-D778-485B-920A-42D4EB3CBA75}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autofac.Extensions.DependencyInjection.Bench", "bench\Autofac.Extensions.DependencyInjection.Bench\Autofac.Extensions.DependencyInjection.Bench.csproj", "{639CD744-1E61-4EF8-9E5A-9920A6BC3891}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{4072A677-5ACA-4CA4-B5EB-9B9DE7D1DD08}"
ProjectSection(SolutionItems) = preProject
build\Analyzers.ruleset = build\Analyzers.ruleset
build\Autofac.Build.psd1 = build\Autofac.Build.psd1
build\Autofac.Build.psm1 = build\Autofac.Build.psm1
build\CodeAnalysisDictionary.xml = build\CodeAnalysisDictionary.xml
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autofac.Extensions.DependencyInjection.Integration.Test", "test\Autofac.Extensions.DependencyInjection.Integration.Test\Autofac.Extensions.DependencyInjection.Integration.Test.csproj", "{D6217688-8E4A-4092-8D78-C4D299F27D7B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Integration.Net8", "test\Integration.Net8\Integration.Net8.csproj", "{549E4C50-7B8F-4E18-92E1-60F036B3515F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Integration.Net10", "test\Integration.Net10\Integration.Net10.csproj", "{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|ARM = Debug|ARM
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|ARM = Release|ARM
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Debug|ARM.ActiveCfg = Debug|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Debug|ARM.Build.0 = Debug|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Debug|x64.ActiveCfg = Debug|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Debug|x64.Build.0 = Debug|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Debug|x86.ActiveCfg = Debug|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Debug|x86.Build.0 = Debug|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Release|Any CPU.Build.0 = Release|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Release|ARM.ActiveCfg = Release|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Release|ARM.Build.0 = Release|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Release|x64.ActiveCfg = Release|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Release|x64.Build.0 = Release|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Release|x86.ActiveCfg = Release|Any CPU
{513C7F7A-A758-4D48-94F4-891A00F63DA1}.Release|x86.Build.0 = Release|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Debug|Any CPU.Build.0 = Debug|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Debug|ARM.ActiveCfg = Debug|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Debug|ARM.Build.0 = Debug|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Debug|x64.ActiveCfg = Debug|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Debug|x64.Build.0 = Debug|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Debug|x86.ActiveCfg = Debug|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Debug|x86.Build.0 = Debug|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Release|Any CPU.ActiveCfg = Release|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Release|Any CPU.Build.0 = Release|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Release|ARM.ActiveCfg = Release|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Release|ARM.Build.0 = Release|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Release|x64.ActiveCfg = Release|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Release|x64.Build.0 = Release|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Release|x86.ActiveCfg = Release|Any CPU
{911AA52A-4E68-41C5-AB24-D1618AFDF753}.Release|x86.Build.0 = Release|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Debug|Any CPU.Build.0 = Debug|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Debug|ARM.ActiveCfg = Debug|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Debug|ARM.Build.0 = Debug|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Debug|x64.ActiveCfg = Debug|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Debug|x64.Build.0 = Debug|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Debug|x86.ActiveCfg = Debug|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Debug|x86.Build.0 = Debug|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Release|Any CPU.ActiveCfg = Release|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Release|Any CPU.Build.0 = Release|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Release|ARM.ActiveCfg = Release|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Release|ARM.Build.0 = Release|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Release|x64.ActiveCfg = Release|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Release|x64.Build.0 = Release|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Release|x86.ActiveCfg = Release|Any CPU
{639CD744-1E61-4EF8-9E5A-9920A6BC3891}.Release|x86.Build.0 = Release|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Debug|ARM.ActiveCfg = Debug|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Debug|ARM.Build.0 = Debug|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Debug|x64.ActiveCfg = Debug|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Debug|x64.Build.0 = Debug|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Debug|x86.ActiveCfg = Debug|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Debug|x86.Build.0 = Debug|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Release|Any CPU.Build.0 = Release|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Release|ARM.ActiveCfg = Release|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Release|ARM.Build.0 = Release|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Release|x64.ActiveCfg = Release|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Release|x64.Build.0 = Release|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Release|x86.ActiveCfg = Release|Any CPU
{D6217688-8E4A-4092-8D78-C4D299F27D7B}.Release|x86.Build.0 = Release|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Debug|ARM.ActiveCfg = Debug|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Debug|ARM.Build.0 = Debug|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Debug|x64.ActiveCfg = Debug|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Debug|x64.Build.0 = Debug|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Debug|x86.ActiveCfg = Debug|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Debug|x86.Build.0 = Debug|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Release|Any CPU.Build.0 = Release|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Release|ARM.ActiveCfg = Release|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Release|ARM.Build.0 = Release|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Release|x64.ActiveCfg = Release|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Release|x64.Build.0 = Release|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Release|x86.ActiveCfg = Release|Any CPU
{549E4C50-7B8F-4E18-92E1-60F036B3515F}.Release|x86.Build.0 = Release|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Debug|ARM.ActiveCfg = Debug|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Debug|ARM.Build.0 = Debug|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Debug|x64.ActiveCfg = Debug|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Debug|x64.Build.0 = Debug|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Debug|x86.ActiveCfg = Debug|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Debug|x86.Build.0 = Debug|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Release|Any CPU.Build.0 = Release|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Release|ARM.ActiveCfg = Release|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Release|ARM.Build.0 = Release|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Release|x64.ActiveCfg = Release|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Release|x64.Build.0 = Release|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Release|x86.ActiveCfg = Release|Any CPU
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{513C7F7A-A758-4D48-94F4-891A00F63DA1} = {5A54DF18-E3F3-4929-876D-00650A15763E}
{911AA52A-4E68-41C5-AB24-D1618AFDF753} = {DEA4A8C6-DE56-4359-A87C-472FB34132E7}
{639CD744-1E61-4EF8-9E5A-9920A6BC3891} = {C39BE99E-D778-485B-920A-42D4EB3CBA75}
{D6217688-8E4A-4092-8D78-C4D299F27D7B} = {DEA4A8C6-DE56-4359-A87C-472FB34132E7}
{549E4C50-7B8F-4E18-92E1-60F036B3515F} = {DEA4A8C6-DE56-4359-A87C-472FB34132E7}
{3514BA96-C0C2-44A5-95EF-EF3F54219CDC} = {DEA4A8C6-DE56-4359-A87C-472FB34132E7}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {76E0A652-E5E2-4CA4-BAFD-AF6FDE0BD56A}
EnterpriseLibraryConfigurationToolBinariesPath = packages\Unity.2.1.505.0\lib\NET35;packages\Unity.Interception.2.1.505.0\lib\NET35;packages\EnterpriseLibrary.Common.5.0.505.0\lib\NET35;packages\EnterpriseLibrary.ExceptionHandling.5.0.505.0\lib\NET35;packages\Unity.2.1.505.2\lib\NET35;packages\Unity.Interception.2.1.505.2\lib\NET35
EndGlobalSection
EndGlobal
================================================
FILE: Autofac.Extensions.DependencyInjection.sln.DotSettings
================================================
True
================================================
FILE: Directory.Build.props
================================================
true
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright © 2014 Autofac Project
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.
================================================
FILE: README.md
================================================
# Autofac.Extensions.DependencyInjection
Autofac is an [IoC container](http://martinfowler.com/articles/injection.html) for Microsoft .NET. It manages the dependencies between classes so that **applications stay easy to change as they grow** in size and complexity. This is achieved by treating regular .NET classes as *[components](https://autofac.readthedocs.io/en/latest/glossary.html)*.
[](https://ci.appveyor.com/project/Autofac/autofac-extensions-dependencyinjection/branch/develop) [](https://codecov.io/gh/Autofac/Autofac.Extensions.DependencyInjection)
Please file issues and pull requests for this package in this repository rather than in the Autofac core repo.
- [Documentation - .NET Core Integration](https://autofac.readthedocs.io/en/latest/integration/netcore.html)
- [Documentation - ASP.NET Core Integration](https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html)
- [NuGet](https://www.nuget.org/packages/Autofac.Extensions.DependencyInjection)
- [Contributing](https://autofac.readthedocs.io/en/latest/contributors.html)
- [Open in Visual Studio Code](https://open.vscode.dev/autofac/Autofac.Extensions.DependencyInjection)
## Get Started in ASP.NET Core
This quick start shows how to use the `IServiceProviderFactory{T}` integration that ASP.NET Core supports to help automatically build the root service provider for you. If you want more manual control, [check out the documentation for examples](https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html).
- Reference the `Autofac.Extensions.DependencyInjection` package from NuGet.
- In your `Program.Main` method, where you configure the `HostBuilder`, call `UseAutofac` to hook Autofac into the startup pipeline.
- In the `ConfigureServices` method of your `Startup` class register things into the `IServiceCollection` using extension methods provided by other libraries.
- In the `ConfigureContainer` method of your `Startup` class register things directly into an Autofac `ContainerBuilder`.
The `IServiceProvider` will automatically be created for you, so there's nothing you have to do but *register things*.
```C#
public class Program
{
public static async Task Main(string[] args)
{
// The service provider factory used here allows for
// ConfigureContainer to be supported in Startup with
// a strongly-typed ContainerBuilder.
var host = Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webHostBuilder => {
webHostBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup()
})
.Build();
await host.RunAsync();
}
}
public class Startup
{
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfiguration Configuration { get; private set; }
// ConfigureServices is where you register dependencies. This gets
// called by the runtime before the ConfigureContainer method, below.
public void ConfigureServices(IServiceCollection services)
{
// Add services to the collection. Don't build or return
// any IServiceProvider or the ConfigureContainer method
// won't get called.
services.AddOptions();
}
// ConfigureContainer is where you can register things directly
// with Autofac. This runs after ConfigureServices so the things
// here will override registrations made in ConfigureServices.
// Don't build the container; that gets done for you. If you
// need a reference to the container, you need to use the
// "Without ConfigureContainer" mechanism shown later.
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new AutofacModule());
}
// Configure is where you add middleware. This is called after
// ConfigureContainer. You can use IApplicationBuilder.ApplicationServices
// here if you need to resolve things from the container.
public void Configure(
IApplicationBuilder app,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
```
Our [ASP.NET Core](https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html) integration documentation contains more information about using Autofac with ASP.NET Core.
## 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).
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/Autofac.Extensions.DependencyInjection.Bench.csproj
================================================
net10.0
$(NoWarn);CS1591
Exe
false
$([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)
latest
enable
true
../../build/Test.ruleset
true
AllEnabledByDefault
enable
false
true
true
true
all
runtime; build; native; contentfiles; analyzers; buildtransitive
all
runtime; build; native; contentfiles; analyzers; buildtransitive
all
runtime; build; native; contentfiles; analyzers
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/AutofacWebApplicationFactory.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.Extensions.Hosting;
namespace Autofac.Extensions.DependencyInjection.Bench;
public sealed class AutofacWebApplicationFactory : BenchWebApplicationFactory
where TStartup : class
{
protected override IHost CreateHost(IHostBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.UseServiceProviderFactory(new AutofacServiceProviderFactory());
return base.CreateHost(builder);
}
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/BenchWebApplicationFactory.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.IO;
using System.Threading;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Hosting;
namespace Autofac.Extensions.DependencyInjection.Bench;
public abstract class BenchWebApplicationFactory : WebApplicationFactory
where TStartup : class
{
private static readonly Lazy ContentRoot = new(ResolveContentRoot, LazyThreadSafetyMode.ExecutionAndPublication);
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);
base.ConfigureWebHost(builder);
builder.UseContentRoot(ContentRoot.Value);
}
private static string ResolveContentRoot() =>
Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", ".."));
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/BenchmarkConfig.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
namespace Autofac.Extensions.DependencyInjection.Bench;
internal sealed class BenchmarkConfig : ManualConfig
{
private const string BenchmarkArtifactsFolder = "BenchmarkDotNet.Artifacts";
internal BenchmarkConfig()
{
Add(DefaultConfig.Instance);
var rootFolder = AppContext.BaseDirectory.Substring(0, AppContext.BaseDirectory.LastIndexOf("bin", StringComparison.OrdinalIgnoreCase));
var runFolder = DateTime.Now.ToString("u").Replace(' ', '_').Replace(':', '-');
ArtifactsPath = Path.Combine(rootFolder, BenchmarkArtifactsFolder, runFolder);
AddDiagnoser(MemoryDiagnoser.Default);
}
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/Benchmarks.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Autofac.Extensions.DependencyInjection.Bench;
public static class Benchmarks
{
public static readonly Type[] All =
{
typeof(RequestBenchmark),
typeof(KeyedResolutionBenchmark),
};
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/DefaultWebApplicationFactory.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Autofac.Extensions.DependencyInjection.Bench;
public sealed class DefaultWebApplicationFactory : BenchWebApplicationFactory
where TStartup : class
{
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/Harness.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using BenchmarkDotNet.Running;
namespace Autofac.Extensions.DependencyInjection.Bench;
public class Harness
{
[Fact]
public void Request() => RunBenchmark();
[Fact]
public void KeyedResolution() => RunBenchmark();
///
/// This method is used to enforce that benchmark types are added to
/// so that they can be used directly from the command line in as well.
///
private static void RunBenchmark()
{
var targetType = typeof(TBenchmark);
var benchmarkType = Benchmarks.All.Single(type => type == targetType);
BenchmarkRunner.Run(benchmarkType, new BenchmarkConfig());
}
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/KeyedResolutionBenchmark.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using MicrosoftServiceKey = Microsoft.Extensions.DependencyInjection.ServiceKeyAttribute;
namespace Autofac.Extensions.DependencyInjection.Bench;
[MemoryDiagnoser]
[SuppressMessage("CA1001", "CA1001", Justification = "Benchmark disposal happens in GlobalCleanup.")]
public class KeyedResolutionBenchmark
{
private const string AlphaKey = "alpha";
private const string BetaKey = "beta";
private const string ServiceKeyAwareKey = "gamma";
private const string CombinedKey = "combined";
private AutofacServiceProvider _serviceProvider = null!;
private ILifetimeScope _rootScope = null!;
[GlobalSetup]
public void Setup()
{
var services = new ServiceCollection();
services.AddTransient();
services.AddKeyedTransient(AlphaKey);
services.AddKeyedTransient(BetaKey);
services.AddKeyedTransient(ServiceKeyAwareKey);
services.AddTransient();
services.AddKeyedTransient(CombinedKey);
var builder = new ContainerBuilder();
builder.Populate(services);
_rootScope = builder.Build();
_serviceProvider = new AutofacServiceProvider(_rootScope);
}
[GlobalCleanup]
public void Cleanup()
{
_serviceProvider.Dispose();
}
[Benchmark(Baseline = true)]
public int StandardTypedResolution()
{
return _serviceProvider.GetRequiredService().Value;
}
[Benchmark]
public int KeyedResolutionWithoutAttributes()
{
return _serviceProvider.GetRequiredKeyedService(AlphaKey).Value;
}
[Benchmark]
public int KeyedResolutionWithServiceKeyAttribute()
{
return _serviceProvider.GetRequiredKeyedService(ServiceKeyAwareKey).Value;
}
[Benchmark]
public int KeyedResolutionWithFromKeyedServicesAttribute()
{
return _serviceProvider.GetRequiredService().Value;
}
[Benchmark]
public int KeyedResolutionWithBothAttributes()
{
return _serviceProvider.GetRequiredKeyedService(CombinedKey).Value;
}
[Benchmark]
public int KeyedResolutionWithAnyKey()
{
var result = _serviceProvider.GetKeyedServices(KeyedService.AnyKey);
var total = 0;
foreach (var service in result)
{
total += service.Value;
}
return total;
}
private interface IService
{
int Value { get; }
}
private sealed class DefaultService : IService
{
public int Value => 1;
}
private sealed class AlphaService : IService
{
public int Value => 2;
}
private sealed class BetaService : IService
{
public int Value => 3;
}
private sealed class FromKeyedServicesConsumer
{
private readonly IService _service;
public FromKeyedServicesConsumer([FromKeyedServices(BetaKey)] IService service)
{
_service = service;
}
public int Value => _service.Value;
}
private sealed class CombinedConsumer
{
private readonly IService _fromKeyedService;
private readonly object? _requestedKey;
public CombinedConsumer(
[FromKeyedServices(BetaKey)] IService fromKeyedService,
[MicrosoftServiceKey] object? requestedKey)
{
_fromKeyedService = fromKeyedService;
_requestedKey = requestedKey;
}
public int Value
{
get
{
var keyValue = _requestedKey is string s ? s.Length : 0;
return _fromKeyedService.Value + keyValue;
}
}
}
private sealed class ServiceKeyAwareService : IService
{
private readonly string _resolvedKey;
public ServiceKeyAwareService([MicrosoftServiceKey] string resolvedKey)
{
_resolvedKey = resolvedKey;
}
public int Value => _resolvedKey.Length;
}
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/Program.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using Microsoft.Extensions.Hosting;
namespace Autofac.Extensions.DependencyInjection.Bench;
public sealed class Program
{
private Program()
{
}
public static void Main(string[] args)
{
ArgumentNullException.ThrowIfNull(args);
var (filteredArgs, baselineVersion) = ExtractBaselineVersion(args);
// Usage:
//
// Just run the benchmark with the source code version of the project:
// dotnet run -c Release -p bench/Autofac.Extensions.DependencyInjection.Bench
//
// Run the benchmark comparing the source code version to a specific package version:
// dotnet run -c Release -p bench/Autofac.Extensions.DependencyInjection.Bench -- --baseline-version 9.0.0
var config = new BenchmarkConfig();
config.AddJob(
Job.InProcess
.WithId("Source"));
if (!string.IsNullOrWhiteSpace(baselineVersion))
{
config.AddJob(
Job.Default
.WithId($"Package-{baselineVersion}")
.AsBaseline()
.WithMsBuildArguments(
"/p:UseProjectReference=false",
$"/p:BaselinePackageVersion={baselineVersion}"));
}
new BenchmarkSwitcher(Benchmarks.All).Run(filteredArgs, config);
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
SampleApp.Program.CreateHostBuilder(args);
private static (string[] RemainingArgs, string? BaselineVersion) ExtractBaselineVersion(string[] args)
{
var forwarded = new List(args.Length);
string? baseline = null;
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (TryMatchBaselineArg(arg, out var inlineVersion))
{
if (!string.IsNullOrWhiteSpace(inlineVersion))
{
baseline = inlineVersion;
continue;
}
if (i + 1 >= args.Length)
{
throw new ArgumentException("Missing version value for baseline argument.", nameof(args));
}
baseline = args[++i];
continue;
}
forwarded.Add(arg);
}
return (forwarded.ToArray(), baseline);
}
private static bool TryMatchBaselineArg(string arg, out string? valueFromAssignment)
{
valueFromAssignment = null;
static bool Matches(string candidate) =>
candidate.Equals("--baseline-version", StringComparison.OrdinalIgnoreCase) ||
candidate.Equals("--baselineVersion", StringComparison.OrdinalIgnoreCase);
var equalsIndex = arg.AsSpan().IndexOf('=');
if (equalsIndex >= 0)
{
var prefix = arg[..equalsIndex];
if (Matches(prefix))
{
valueFromAssignment = arg[(equalsIndex + 1)..];
return true;
}
return false;
}
return Matches(arg);
}
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/Properties/AssemblyInfo.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
[assembly: CLSCompliant(false)]
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/RequestBenchmark.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
namespace Autofac.Extensions.DependencyInjection.Bench;
[SuppressMessage("CA1001", "CA1001", Justification = "Benchmark disposal happens in a global cleanup method.")]
public class RequestBenchmark
{
private static readonly Uri ValuesUri = new("/api/values", UriKind.Relative);
private WebApplicationFactory _defaultFactory = null!;
private WebApplicationFactory _autofacFactory = null!;
private HttpClient _defaultClient = null!;
private HttpClient _autofacClient = null!;
[GlobalSetup]
public void Setup()
{
_defaultFactory = new DefaultWebApplicationFactory();
_autofacFactory = new AutofacWebApplicationFactory();
_defaultClient = _defaultFactory.CreateClient();
_autofacClient = _autofacFactory.CreateClient();
}
[GlobalCleanup]
public void Cleanup()
{
_defaultFactory.Dispose();
_autofacFactory.Dispose();
}
[Benchmark(Baseline = true)]
public async Task RequestDefaultDI()
{
var response = await _defaultClient.GetAsync(ValuesUri).ConfigureAwait(false);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new HttpRequestException();
}
}
[Benchmark]
public async Task RequestAutofacDI()
{
var response = await _autofacClient.GetAsync(ValuesUri).ConfigureAwait(false);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new HttpRequestException();
}
}
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/SampleApp/Controllers/ValuesController.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.AspNetCore.Mvc;
namespace Autofac.Extensions.DependencyInjection.Bench.SampleApp.Controllers;
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly A _service;
public ValuesController(A service)
{
_service = service;
}
[HttpGet]
public IActionResult Get()
{
return Ok(200);
}
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/SampleApp/DefaultStartup.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Autofac.Extensions.DependencyInjection.Bench.SampleApp;
public class DefaultStartup
{
public DefaultStartup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/SampleApp/Program.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Autofac.Extensions.DependencyInjection.Bench.SampleApp;
public sealed class Program
{
private Program()
{
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.SetMinimumLevel(LogLevel.Warning);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
}
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/SampleApp/Services.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#pragma warning disable SA1402, SA1649
namespace Autofac.Extensions.DependencyInjection.Bench.SampleApp;
public class A
{
public A(B1 b1, B2 b2)
{
}
}
public class B1
{
public B1(B2 b2, C1 c1, C2 c2)
{
}
}
public class B2
{
public B2(C1 c1, C2 c2)
{
}
}
public class C1
{
public C1(C2 c2, D1 d1, D2 d2)
{
}
}
public class C2
{
public C2(D1 d1, D2 d2)
{
}
}
public class D1
{
}
public class D2
{
}
#pragma warning restore SA1402, SA1649
================================================
FILE: bench/Autofac.Extensions.DependencyInjection.Bench/xunit.runner.json
================================================
{
"shadowCopy": false
}
================================================
FILE: build/Coverage.runsettings
================================================
cobertura
[System.*]*
**/LoggerMessage.g.cs
GeneratedCodeAttribute
false
true
false
================================================
FILE: build/Source.ruleset
================================================
================================================
FILE: build/Test.ruleset
================================================
================================================
FILE: build/stylecop.json
================================================
{
"$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
}
}
}
================================================
FILE: codecov.yml
================================================
codecov:
branch: develop
require_ci_to_pass: true
coverage:
status:
project:
default:
threshold: 1%
================================================
FILE: default.proj
================================================
11.0.0
Autofac.Extensions.DependencyInjection
Release
$([System.IO.Path]::Combine($(MSBuildProjectDirectory),"artifacts"))
$([System.IO.Path]::Combine($(ArtifactDirectory),"packages"))
$([System.IO.Path]::Combine($(ArtifactDirectory),"logs"))
$([System.IO.Path]::Combine($(MSBuildProjectDirectory),'build/Coverage.runsettings'))
$([System.DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssZ'))
$(Version)-local
$(Version)
$(Version)-beta$(BuildDateTime)
$(Version)-alpha$(BuildDateTime)
================================================
FILE: global.json
================================================
{
"sdk": {
"rollForward": "latestFeature",
"version": "10.0.100"
}
}
================================================
FILE: src/Autofac.Extensions.DependencyInjection/Autofac.Extensions.DependencyInjection.csproj
================================================
Autofac.Extensions.DependencyInjection
Autofac.Extensions.DependencyInjection
Autofac implementation of the interfaces in Microsoft.Extensions.DependencyInjection.Abstractions, the .NET Framework dependency injection abstraction.
Copyright © 2015 Autofac Contributors
Autofac Contributors
Autofac
Autofac
../../Autofac.snk
true
en-US
net10.0;net8.0;netstandard2.1;netstandard2.0
latest
enable
true
../../build/Source.ruleset
true
AllEnabledByDefault
enable
Autofac.Extensions.DependencyInjection
autofac;di;ioc;dependencyinjection;aspnet;aspnetcore
Release notes are at https://github.com/autofac/Autofac.Extensions.DependencyInjection/releases
icon.png
https://autofac.org
MIT
README.md
git
https://github.com/autofac/Autofac.Extensions.DependencyInjection
true
true
true
true
snupkg
PrepareResources;$(CompileDependsOn)
$(NoWarn);8765;8600;8601;8602;8603;8604
all
all
MSBuild:Compile
CSharp
$(IntermediateOutputPath)%(Filename).Designer.cs
%(Filename)
Autofac.Extensions.DependencyInjection
Autofac.Extensions.DependencyInjection
Autofac.Extensions.DependencyInjection
================================================
FILE: src/Autofac.Extensions.DependencyInjection/AutofacChildLifetimeScopeConfigurationAdapter.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Autofac.Extensions.DependencyInjection;
///
/// Configuration adapter for .
///
public class AutofacChildLifetimeScopeConfigurationAdapter
{
private readonly List> _configurationActions = new();
///
/// Gets the list of configuration actions to be executed on the for the child .
///
public IReadOnlyList> ConfigurationActions => _configurationActions;
///
/// Adds a configuration action that will be executed when the child is created.
///
/// Action on a that adds component registrations to the container.
/// Throws when the passed configuration-action is null.
public void Add(Action configurationAction)
{
if (configurationAction == null)
{
throw new ArgumentNullException(nameof(configurationAction));
}
_configurationActions.Add(configurationAction);
}
}
================================================
FILE: src/Autofac.Extensions.DependencyInjection/AutofacChildLifetimeScopeServiceProviderFactory.cs
================================================
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.Extensions.DependencyInjection;
namespace Autofac.Extensions.DependencyInjection;
///
/// A factory for creating a that wraps a child created from an existing parent .
///
public class AutofacChildLifetimeScopeServiceProviderFactory : IServiceProviderFactory
{
private static readonly Action FallbackConfigurationAction = builder => { };
private readonly Action _containerConfigurationAction;
private readonly ILifetimeScope _rootLifetimeScope;
///
/// Initializes a new instance of the class.
///
/// A function to retrieve the root instance.
/// Action on a that adds component registrations to the container.
public AutofacChildLifetimeScopeServiceProviderFactory(Func rootLifetimeScopeAccessor, Action? configurationAction = null)
{
if (rootLifetimeScopeAccessor == null)
{
throw new ArgumentNullException(nameof(rootLifetimeScopeAccessor));
}
_rootLifetimeScope = rootLifetimeScopeAccessor();
_containerConfigurationAction = configurationAction ?? FallbackConfigurationAction;
}
///
/// Initializes a new instance of the class.
///
/// The root instance.
/// Action on a that adds component registrations to the container.
public AutofacChildLifetimeScopeServiceProviderFactory(ILifetimeScope rootLifetimeScope, Action? configurationAction = null)
{
_rootLifetimeScope = rootLifetimeScope ?? throw new ArgumentNullException(nameof(rootLifetimeScope));
_containerConfigurationAction = configurationAction ?? FallbackConfigurationAction;
}
///
/// Creates a container builder from an .
///
/// The collection of services.
/// A container builder that can be used to create an .
public AutofacChildLifetimeScopeConfigurationAdapter CreateBuilder(IServiceCollection services)
{
var actions = new AutofacChildLifetimeScopeConfigurationAdapter();
actions.Add(builder => builder.Populate(services));
actions.Add(builder => _containerConfigurationAction(builder));
return actions;
}
///
/// Creates an from the container builder.
///
/// The adapter holding configuration applied to creating the .
/// An .
public IServiceProvider CreateServiceProvider(AutofacChildLifetimeScopeConfigurationAdapter containerBuilder)
{
if (containerBuilder == null)
{
throw new ArgumentNullException(nameof(containerBuilder));
}
var scope = _rootLifetimeScope.BeginLifetimeScope(scopeBuilder =>
{
foreach (var action in containerBuilder.ConfigurationActions)
{
action(scopeBuilder);
}
});
return new AutofacServiceProvider(scope);
}
}
================================================
FILE: src/Autofac.Extensions.DependencyInjection/AutofacRegistration.cs
================================================
// 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 Autofac.Builder;
using Autofac.Core;
using Autofac.Core.Activators;
using Autofac.Core.Activators.Delegate;
using Autofac.Core.Activators.Reflection;
using Autofac.Core.Resolving.Pipeline;
using Microsoft.Extensions.DependencyInjection;
namespace Autofac.Extensions.DependencyInjection;
///
/// Extension methods for registering ASP.NET Core dependencies with Autofac.
///
public static class AutofacRegistration
{
///
/// Populates the Autofac container builder with the set of registered service descriptors
/// and makes and
/// available in the container.
///
///
/// The into which the registrations should be made.
///
///
/// The set of service descriptors to register in the container.
///
public static void Populate(
this ContainerBuilder builder,
IEnumerable descriptors)
{
Populate(builder, descriptors, null);
}
///
/// Populates the Autofac container builder with the set of registered service descriptors
/// and makes and
/// available in the container. Using this overload is incompatible with the ASP.NET Core
/// support for .
///
///
/// The into which the registrations should be made.
///
///
/// The set of service descriptors to register in the container.
///
///
/// If provided and not then all registrations with lifetime are registered
/// using
/// with provided
/// instead of using .
///
///
///
/// Specifying a addresses a specific case where you have
/// an application that uses Autofac but where you need to isolate a set of services in a child scope. For example,
/// if you have a large application that self-hosts ASP.NET Core items, you may want to isolate the ASP.NET
/// Core registrations in a child lifetime scope so they don't show up for the rest of the application.
/// This overload allows that. Note it is the developer's responsibility to execute this and create an
/// using the child lifetime scope.
///
///
public static void Populate(
this ContainerBuilder builder,
IEnumerable descriptors,
object? lifetimeScopeTagForSingletons)
{
if (descriptors is null)
{
throw new ArgumentNullException(nameof(descriptors));
}
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.RegisterType()
.As()
.As()
.As()
.As()
.ExternallyOwned();
// Issue #83: IServiceScopeFactory must be a singleton and scopes must be flat, not hierarchical.
builder
.RegisterType()
.As()
.SingleInstance();
// Shims for keyed service compatibility.
builder.ComponentRegistryBuilder.Registered += AddFromKeyedServiceParameterMiddleware;
Register(builder, descriptors, lifetimeScopeTagForSingletons);
}
///
/// Inspect each component registration, and determine whether or not we can avoid adding the
/// parameter to the resolve pipeline.
///
private static void AddFromKeyedServiceParameterMiddleware(object? sender, ComponentRegisteredEventArgs e)
{
var needFromKeyedServiceParameter = false;
// We can optimize quite significantly in the case where we are using
// the reflection activator. In that state we can inspect the
// constructors ahead of time and determine whether the parameter will
// even need to be added.
if (e.ComponentRegistration.Activator is ReflectionActivator reflectionActivator)
{
needFromKeyedServiceParameter = FromKeyedServicesUsageCache.RequiresFromKeyedServicesMiddleware(reflectionActivator);
}
else if (e.ComponentRegistration.Activator is DelegateActivator)
{
// For delegate activation there are very few paths that would let
// the FromKeyedServicesAttribute actually work, and none that MEDI
// supports directly.
//
// We're explicitly choosing here not to support [FromKeyedServices]
// on the Autofac-specific generic delegate resolve methods, to
// improve performance for the 99% case of other delegates that only
// receive an IComponentContext or an IServiceProvider.
needFromKeyedServiceParameter = false;
}
else if (e.ComponentRegistration.Activator is InstanceActivator)
{
// Instance activators don't use parameters.
needFromKeyedServiceParameter = false;
}
else
{
// Unknown activator, assume we need the parameter.
needFromKeyedServiceParameter = true;
}
e.ComponentRegistration.PipelineBuilding += (sender, pipeline) =>
{
if (needFromKeyedServiceParameter)
{
pipeline.Use(KeyedServiceMiddleware.InstanceWithFromKeyedServicesParameter, MiddlewareInsertionMode.StartOfPhase);
}
else
{
pipeline.Use(KeyedServiceMiddleware.InstanceWithoutFromKeyedServicesParameter, MiddlewareInsertionMode.StartOfPhase);
}
};
}
///
/// Configures the exposed service type on a service registration.
///
/// The activator data type.
/// The object registration style.
/// The registration being built.
/// The service descriptor with service type and key information.
///
/// The , configured with the proper service type,
/// and available for additional configuration.
///
private static IRegistrationBuilder