├── .markdownlint.json
├── Autofac.snk
├── bench
├── Autofac.Extensions.DependencyInjection.Bench
│ ├── xunit.runner.json
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Benchmarks.cs
│ ├── Program.cs
│ ├── AutofacWebApplicationFactory.cs
│ ├── Harness.cs
│ ├── BenchmarkConfig.cs
│ ├── RequestBenchmark.cs
│ └── Autofac.Extensions.DependencyInjection.Bench.csproj
└── projects
│ └── Bench.AutofacApiServer
│ ├── Properties
│ ├── AssemblyInfo.cs
│ └── launchSettings.json
│ ├── appsettings.json
│ ├── Controllers
│ └── ValuesController.cs
│ ├── Program.cs
│ ├── Services.cs
│ ├── BenchProject.AutofacApiServer.csproj
│ └── DefaultStartup.cs
├── global.json
├── test
├── Integration.Net6
│ ├── appsettings.json
│ ├── appsettings.Development.json
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ └── launchSettings.json
│ ├── IDateProvider.cs
│ ├── DateProvider.cs
│ ├── Controllers
│ │ └── DateController.cs
│ ├── Program.cs
│ ├── Startup.cs
│ └── Integration.Net6.csproj
├── Integration.Net7
│ ├── appsettings.json
│ ├── appsettings.Development.json
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ └── launchSettings.json
│ ├── IDateProvider.cs
│ ├── DateProvider.cs
│ ├── Controllers
│ │ └── DateController.cs
│ ├── Program.cs
│ ├── Startup.cs
│ └── Integration.Net7.csproj
├── Integration.Net8
│ ├── appsettings.json
│ ├── appsettings.Development.json
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ └── launchSettings.json
│ ├── IDateProvider.cs
│ ├── DateProvider.cs
│ ├── Controllers
│ │ └── DateController.cs
│ ├── Program.cs
│ ├── Startup.cs
│ └── Integration.Net8.csproj
├── Autofac.Extensions.DependencyInjection.Test
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Specification
│ │ ├── MicrosoftAssumedBehaviorTests.cs
│ │ ├── FactoryAssumedBehaviorTests.cs
│ │ ├── BuilderAssumedBehaviorTests.cs
│ │ ├── FactorySpecificationTests.cs
│ │ ├── FactoryKeyedSpecificationTests.cs
│ │ ├── ChildScopeFactoryAssumedBehaviorTests.cs
│ │ ├── BuilderSpecificationTests.cs
│ │ ├── BuilderKeyedSpecificationTests.cs
│ │ ├── ChildScopeFactorySpecificationTests.cs
│ │ ├── ChildScopeFactoryKeyedSpecificationTests.cs
│ │ └── AssumedBehaviorTests.cs
│ ├── AutofacChildLifetimeScopeConfigurationAdapterTests.cs
│ ├── ServiceProviderExtensionsTests.cs
│ ├── TestCulture.cs
│ ├── ServiceCollectionExtensionsTests.cs
│ ├── Assertions.cs
│ ├── Autofac.Extensions.DependencyInjection.Test.csproj
│ ├── AutofacServiceProviderFactoryTests.cs
│ ├── TypeManipulationFixture.cs
│ ├── AutofacChildLifetimeScopeServiceProviderFactoryTests.cs
│ └── AutofacRegistrationTests.cs
└── Autofac.Extensions.DependencyInjection.Integration.Test
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── IntegrationTests.cs
│ └── Autofac.Extensions.DependencyInjection.Integration.Test.csproj
├── codecov.yml
├── .vscode
├── extensions.json
├── settings.json
├── launch.json
└── tasks.json
├── Directory.Build.props
├── .github
└── workflows
│ ├── pre-commit.yml
│ ├── dotnet-format.yml
│ ├── build.yml
│ ├── ci.yml
│ └── publish.yml
├── NuGet.Config
├── Autofac.Extensions.DependencyInjection.sln.DotSettings
├── src
└── Autofac.Extensions.DependencyInjection
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── ServiceCollectionExtensions.cs
│ ├── ServiceProviderExtensions.cs
│ ├── AutofacChildLifetimeScopeConfigurationAdapter.cs
│ ├── ServiceDescriptorExtensions.cs
│ ├── AutofacServiceScopeFactory.cs
│ ├── AutofacServiceScope.cs
│ ├── FromKeyedServicesAttributeExtensions.cs
│ ├── AutofacServiceProviderFactory.cs
│ ├── AutofacChildLifetimeScopeServiceProviderFactory.cs
│ ├── KeyedServiceMiddleware.cs
│ ├── Autofac.Extensions.DependencyInjection.csproj
│ ├── AnyKeyRegistrationSource.cs
│ ├── KeyTypeConversionException.cs
│ ├── KeyTypeConversionExceptionResources.resx
│ ├── ServiceProviderExtensionsResources.resx
│ ├── KeyTypeManipulationResources.resx
│ ├── AutofacServiceProvider.cs
│ └── KeyTypeManipulation.cs
├── .pre-commit-config.yaml
├── .gitattributes
├── LICENSE
├── .gitignore
├── default.proj
├── README.md
├── .editorconfig
└── Autofac.Extensions.DependencyInjection.sln
/.markdownlint.json:
--------------------------------------------------------------------------------
1 | {
2 | "MD013": false
3 | }
4 |
--------------------------------------------------------------------------------
/Autofac.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/autofac/Autofac.Extensions.DependencyInjection/HEAD/Autofac.snk
--------------------------------------------------------------------------------
/bench/Autofac.Extensions.DependencyInjection.Bench/xunit.runner.json:
--------------------------------------------------------------------------------
1 | {
2 | "shadowCopy": false
3 | }
4 |
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "rollForward": "latestFeature",
4 | "version": "8.0.414"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/test/Integration.Net6/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "None"
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/test/Integration.Net7/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "None"
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/test/Integration.Net8/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "None"
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/test/Integration.Net6/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information"
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/test/Integration.Net7/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information"
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/test/Integration.Net8/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information"
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/codecov.yml:
--------------------------------------------------------------------------------
1 | codecov:
2 | branch: develop
3 | require_ci_to_pass: true
4 | coverage:
5 | status:
6 | project:
7 | default:
8 | threshold: 1%
9 |
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": [
3 | "davidanson.vscode-markdownlint",
4 | "editorconfig.editorconfig",
5 | "ms-dotnettools.csdevkit",
6 | "travisillig.vscode-json-stable-stringify"
7 | ]
8 | }
9 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | true
5 |
6 |
7 |
--------------------------------------------------------------------------------
/bench/projects/Bench.AutofacApiServer/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | [assembly: CLSCompliant(false)]
5 |
--------------------------------------------------------------------------------
/test/Integration.Net6/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | [assembly: CLSCompliant(false)]
7 |
--------------------------------------------------------------------------------
/test/Integration.Net7/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | [assembly: CLSCompliant(false)]
7 |
--------------------------------------------------------------------------------
/test/Integration.Net8/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | [assembly: CLSCompliant(false)]
7 |
--------------------------------------------------------------------------------
/bench/Autofac.Extensions.DependencyInjection.Bench/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | [assembly: CLSCompliant(false)]
5 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | [assembly: CLSCompliant(false)]
5 |
--------------------------------------------------------------------------------
/bench/projects/Bench.AutofacApiServer/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "AllowedHosts": "*",
3 | "Logging": {
4 | "LogLevel": {
5 | "Default": "Information",
6 | "Microsoft": "Warning",
7 | "Microsoft.Hosting.Lifetime": "Information"
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Integration.Test/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | [assembly: CLSCompliant(false)]
7 |
--------------------------------------------------------------------------------
/.github/workflows/pre-commit.yml:
--------------------------------------------------------------------------------
1 | name: pre-commit
2 | on:
3 | workflow_call:
4 | jobs:
5 | pre-commit:
6 | runs-on: ubuntu-latest
7 | steps:
8 | - uses: actions/checkout@v4
9 | - uses: actions/setup-python@v5
10 | with:
11 | python-version: 3.x
12 | - uses: pre-commit/action@v3.0.1
13 |
--------------------------------------------------------------------------------
/test/Integration.Net6/IDateProvider.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace Integration.Net6;
7 |
8 | public interface IDateProvider
9 | {
10 | DateTimeOffset GetDate();
11 | }
12 |
--------------------------------------------------------------------------------
/test/Integration.Net7/IDateProvider.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace Integration.Net7;
7 |
8 | public interface IDateProvider
9 | {
10 | DateTimeOffset GetDate();
11 | }
12 |
--------------------------------------------------------------------------------
/test/Integration.Net8/IDateProvider.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace Integration.Net8;
7 |
8 | public interface IDateProvider
9 | {
10 | DateTimeOffset GetDate();
11 | }
12 |
--------------------------------------------------------------------------------
/NuGet.Config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/test/Integration.Net6/DateProvider.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace Integration.Net6;
7 |
8 | public class DateProvider : IDateProvider
9 | {
10 | public DateTimeOffset GetDate() => DateTimeOffset.UtcNow;
11 | }
12 |
--------------------------------------------------------------------------------
/test/Integration.Net7/DateProvider.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace Integration.Net7;
7 |
8 | public class DateProvider : IDateProvider
9 | {
10 | public DateTimeOffset GetDate() => DateTimeOffset.UtcNow;
11 | }
12 |
--------------------------------------------------------------------------------
/test/Integration.Net8/DateProvider.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace Integration.Net8;
7 |
8 | public class DateProvider : IDateProvider
9 | {
10 | public DateTimeOffset GetDate() => DateTimeOffset.UtcNow;
11 | }
12 |
--------------------------------------------------------------------------------
/test/Integration.Net6/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "Integration.Net6": {
4 | "applicationUrl": "https://localhost:7154;http://localhost:7155",
5 | "commandName": "Project",
6 | "dotnetRunMessages": true,
7 | "environmentVariables": {
8 | "ASPNETCORE_ENVIRONMENT": "Development"
9 | },
10 | "launchBrowser": true
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/test/Integration.Net7/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "Integration.Net6": {
4 | "applicationUrl": "https://localhost:7154;http://localhost:7155",
5 | "commandName": "Project",
6 | "dotnetRunMessages": true,
7 | "environmentVariables": {
8 | "ASPNETCORE_ENVIRONMENT": "Development"
9 | },
10 | "launchBrowser": true
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/test/Integration.Net8/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "Integration.Net6": {
4 | "applicationUrl": "https://localhost:7154;http://localhost:7155",
5 | "commandName": "Project",
6 | "dotnetRunMessages": true,
7 | "environmentVariables": {
8 | "ASPNETCORE_ENVIRONMENT": "Development"
9 | },
10 | "launchBrowser": true
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/bench/Autofac.Extensions.DependencyInjection.Bench/Benchmarks.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | namespace Autofac.Extensions.DependencyInjection.Bench;
5 |
6 | public static class Benchmarks
7 | {
8 | public static readonly Type[] All =
9 | {
10 | typeof(RequestBenchmark),
11 | };
12 | }
13 |
--------------------------------------------------------------------------------
/Autofac.Extensions.DependencyInjection.sln.DotSettings:
--------------------------------------------------------------------------------
1 |
2 | True
3 |
--------------------------------------------------------------------------------
/.github/workflows/dotnet-format.yml:
--------------------------------------------------------------------------------
1 | name: dotnet format
2 | on:
3 | workflow_call:
4 | jobs:
5 | dotnet-format:
6 | runs-on: ubuntu-latest
7 | steps:
8 | - uses: actions/checkout@v4
9 | - name: Setup .NET 8
10 | uses: actions/setup-dotnet@v4
11 | with:
12 | dotnet-version: 8.0.x
13 | - name: dotnet format
14 | run: dotnet format Autofac.Extensions.DependencyInjection.sln --verify-no-changes
15 |
--------------------------------------------------------------------------------
/bench/Autofac.Extensions.DependencyInjection.Bench/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using BenchmarkDotNet.Running;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Bench;
7 |
8 | internal static class Program
9 | {
10 | internal static void Main(string[] args) =>
11 | new BenchmarkSwitcher(Benchmarks.All).Run(args, new BenchmarkConfig());
12 | }
13 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/MicrosoftAssumedBehaviorTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Test.Specification;
7 |
8 | public class MicrosoftAssumedBehaviorTests : AssumedBehaviorTests
9 | {
10 | protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection)
11 | {
12 | return serviceCollection.BuildServiceProvider();
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/bench/projects/Bench.AutofacApiServer/Controllers/ValuesController.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.AspNetCore.Mvc;
5 |
6 | namespace BenchProject.AutofacApiServer.Controllers;
7 |
8 | [Route("api/[controller]")]
9 | [ApiController]
10 | public class ValuesController : ControllerBase
11 | {
12 | private readonly A _service;
13 |
14 | public ValuesController(A service)
15 | {
16 | _service = service;
17 | }
18 |
19 | [HttpGet]
20 | public IActionResult Get()
21 | {
22 | return Ok(200);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Runtime.CompilerServices;
5 |
6 | [assembly: InternalsVisibleTo("Autofac.Extensions.DependencyInjection.Test, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
7 | [assembly: CLSCompliant(false)]
8 |
--------------------------------------------------------------------------------
/test/Integration.Net6/Controllers/DateController.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 | using Microsoft.AspNetCore.Mvc;
6 |
7 | namespace Integration.Net6.Controllers;
8 |
9 | [ApiController]
10 | [Route("[controller]")]
11 | public class DateController : ControllerBase
12 | {
13 | public DateController(IDateProvider dateProvider)
14 | {
15 | DateProvider = dateProvider;
16 | }
17 |
18 | public IDateProvider DateProvider { get; }
19 |
20 | [HttpGet]
21 | public ActionResult Get() => DateProvider.GetDate();
22 | }
23 |
--------------------------------------------------------------------------------
/test/Integration.Net7/Controllers/DateController.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 | using Microsoft.AspNetCore.Mvc;
6 |
7 | namespace Integration.Net7.Controllers;
8 |
9 | [ApiController]
10 | [Route("[controller]")]
11 | public class DateController : ControllerBase
12 | {
13 | public DateController(IDateProvider dateProvider)
14 | {
15 | DateProvider = dateProvider;
16 | }
17 |
18 | public IDateProvider DateProvider { get; }
19 |
20 | [HttpGet]
21 | public ActionResult Get() => DateProvider.GetDate();
22 | }
23 |
--------------------------------------------------------------------------------
/test/Integration.Net8/Controllers/DateController.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 | using Microsoft.AspNetCore.Mvc;
6 |
7 | namespace Integration.Net8.Controllers;
8 |
9 | [ApiController]
10 | [Route("[controller]")]
11 | public class DateController : ControllerBase
12 | {
13 | public DateController(IDateProvider dateProvider)
14 | {
15 | DateProvider = dateProvider;
16 | }
17 |
18 | public IDateProvider DateProvider { get; }
19 |
20 | [HttpGet]
21 | public ActionResult Get() => DateProvider.GetDate();
22 | }
23 |
--------------------------------------------------------------------------------
/bench/projects/Bench.AutofacApiServer/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | namespace BenchProject.AutofacApiServer;
5 |
6 | public static class Program
7 | {
8 | public static void Main(string[] args)
9 | {
10 | var host = CreateHostBuilder(args).Build();
11 |
12 | host.Run();
13 | }
14 |
15 | private static IHostBuilder CreateHostBuilder(string[] args) =>
16 | Host.CreateDefaultBuilder(args)
17 | .ConfigureWebHostDefaults(webBuilder =>
18 | {
19 | webBuilder.UseStartup();
20 | });
21 | }
22 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/FactoryAssumedBehaviorTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Test.Specification;
7 |
8 | public class FactoryAssumedBehaviorTests : AssumedBehaviorTests
9 | {
10 | protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection)
11 | {
12 | var factory = new AutofacServiceProviderFactory();
13 | return factory.CreateServiceProvider(factory.CreateBuilder(serviceCollection));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/pre-commit/pre-commit-hooks
3 | rev: "cef0300fd0fc4d2a87a85fa2093c6b283ea36f4b" # v5.0.0
4 | hooks:
5 | - id: check-json
6 | - id: check-yaml
7 | - id: check-merge-conflict
8 | - id: end-of-file-fixer
9 | - id: trailing-whitespace
10 | - repo: https://github.com/igorshubovych/markdownlint-cli
11 | rev: "192ad822316c3a22fb3d3cc8aa6eafa0b8488360" # v0.45.0
12 | hooks:
13 | - id: markdownlint
14 | args:
15 | - --fix
16 | - repo: https://github.com/tillig/json-sort-cli
17 | rev: "009ab2ab49e1f2fa9d6b9dfc31009ceeca055204" # v3.0.0
18 | hooks:
19 | - id: json-sort
20 | args:
21 | - --autofix
22 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/BuilderAssumedBehaviorTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Test.Specification;
7 |
8 | public class BuilderAssumedBehaviorTests : AssumedBehaviorTests
9 | {
10 | protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection)
11 | {
12 | var builder = new ContainerBuilder();
13 | builder.Populate(serviceCollection);
14 | var container = builder.Build();
15 | return container.Resolve();
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/bench/Autofac.Extensions.DependencyInjection.Bench/AutofacWebApplicationFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.AspNetCore.Mvc.Testing;
5 | using Microsoft.Extensions.Hosting;
6 |
7 | namespace Autofac.Extensions.DependencyInjection.Bench;
8 |
9 | public class AutofacWebApplicationFactory : WebApplicationFactory
10 | where TStartup : class
11 | {
12 | protected override IHost CreateHost(IHostBuilder builder)
13 | {
14 | ArgumentNullException.ThrowIfNull(builder);
15 | builder.UseServiceProviderFactory(new AutofacServiceProviderFactory());
16 |
17 | return base.CreateHost(builder);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/test/Integration.Net6/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Threading.Tasks;
5 | using Autofac.Extensions.DependencyInjection;
6 | using Microsoft.AspNetCore.Hosting;
7 | using Microsoft.Extensions.Hosting;
8 |
9 | namespace Integration.Net6;
10 |
11 | public static class Program
12 | {
13 | public static IHostBuilder CreateHostBuilder(string[] args) =>
14 | Host.CreateDefaultBuilder(args)
15 | .UseServiceProviderFactory(new AutofacServiceProviderFactory())
16 | .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup());
17 |
18 | public static async Task Main(string[] args) => await CreateHostBuilder(args).Build().RunAsync().ConfigureAwait(false);
19 | }
20 |
--------------------------------------------------------------------------------
/test/Integration.Net7/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Threading.Tasks;
5 | using Autofac.Extensions.DependencyInjection;
6 | using Microsoft.AspNetCore.Hosting;
7 | using Microsoft.Extensions.Hosting;
8 |
9 | namespace Integration.Net7;
10 |
11 | public static class Program
12 | {
13 | public static IHostBuilder CreateHostBuilder(string[] args) =>
14 | Host.CreateDefaultBuilder(args)
15 | .UseServiceProviderFactory(new AutofacServiceProviderFactory())
16 | .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup());
17 |
18 | public static async Task Main(string[] args) => await CreateHostBuilder(args).Build().RunAsync().ConfigureAwait(false);
19 | }
20 |
--------------------------------------------------------------------------------
/test/Integration.Net8/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Threading.Tasks;
5 | using Autofac.Extensions.DependencyInjection;
6 | using Microsoft.AspNetCore.Hosting;
7 | using Microsoft.Extensions.Hosting;
8 |
9 | namespace Integration.Net8;
10 |
11 | public static class Program
12 | {
13 | public static IHostBuilder CreateHostBuilder(string[] args) =>
14 | Host.CreateDefaultBuilder(args)
15 | .UseServiceProviderFactory(new AutofacServiceProviderFactory())
16 | .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup());
17 |
18 | public static async Task Main(string[] args) => await CreateHostBuilder(args).Build().RunAsync().ConfigureAwait(false);
19 | }
20 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/FactorySpecificationTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 | using Microsoft.Extensions.DependencyInjection.Specification;
6 |
7 | namespace Autofac.Extensions.DependencyInjection.Test;
8 |
9 | public class FactorySpecificationTests : DependencyInjectionSpecificationTests
10 | {
11 | public override bool SupportsIServiceProviderIsService => true;
12 |
13 | protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection)
14 | {
15 | var factory = new AutofacServiceProviderFactory();
16 | return factory.CreateServiceProvider(factory.CreateBuilder(serviceCollection));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/FactoryKeyedSpecificationTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 | using Microsoft.Extensions.DependencyInjection.Specification;
6 |
7 | namespace Autofac.Extensions.DependencyInjection.Test;
8 |
9 | public class FactoryKeyedSpecificationTests : KeyedDependencyInjectionSpecificationTests
10 | {
11 | public override bool SupportsIServiceProviderIsKeyedService => true;
12 |
13 | protected override IServiceProvider CreateServiceProvider(IServiceCollection collection)
14 | {
15 | var factory = new AutofacServiceProviderFactory();
16 | return factory.CreateServiceProvider(factory.CreateBuilder(collection));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/ChildScopeFactoryAssumedBehaviorTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Test.Specification;
7 |
8 | public class ChildScopeFactoryAssumedBehaviorTests : AssumedBehaviorTests
9 | {
10 | protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection)
11 | {
12 | var container = new ContainerBuilder().Build();
13 | var rootScope = container.BeginLifetimeScope();
14 | var factory = new AutofacChildLifetimeScopeServiceProviderFactory(() => rootScope);
15 | return factory.CreateServiceProvider(factory.CreateBuilder(serviceCollection));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/BuilderSpecificationTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 | using Microsoft.Extensions.DependencyInjection.Specification;
6 |
7 | namespace Autofac.Extensions.DependencyInjection.Test;
8 |
9 | public class BuilderSpecificationTests : DependencyInjectionSpecificationTests
10 | {
11 | public override bool SupportsIServiceProviderIsService => true;
12 |
13 | protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection)
14 | {
15 | var builder = new ContainerBuilder();
16 | builder.Populate(serviceCollection);
17 | var container = builder.Build();
18 | return container.Resolve();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/AutofacChildLifetimeScopeConfigurationAdapterTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | namespace Autofac.Extensions.DependencyInjection.Test;
5 |
6 | public sealed class AutofacChildLifetimeScopeConfigurationAdapterTests
7 | {
8 | [Fact]
9 | public void AddMultipleConfigurationContainsConfigurations()
10 | {
11 | var adapter = new AutofacChildLifetimeScopeConfigurationAdapter();
12 | adapter.Add(builder => { });
13 | adapter.Add(builder => { });
14 |
15 | Assert.Equal(2, adapter.ConfigurationActions.Count);
16 | }
17 |
18 | [Fact]
19 | public void AddNullConfigurationThrows()
20 | => Assert.Throws(() => new AutofacChildLifetimeScopeConfigurationAdapter().Add(null));
21 | }
22 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/BuilderKeyedSpecificationTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 | using Microsoft.Extensions.DependencyInjection.Specification;
6 |
7 | namespace Autofac.Extensions.DependencyInjection.Test;
8 |
9 | public class BuilderKeyedSpecificationTests : KeyedDependencyInjectionSpecificationTests
10 | {
11 | public override bool SupportsIServiceProviderIsKeyedService => true;
12 |
13 | protected override IServiceProvider CreateServiceProvider(IServiceCollection collection)
14 | {
15 | var builder = new ContainerBuilder();
16 | builder.Populate(collection);
17 | var container = builder.Build();
18 | return container.Resolve();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/bench/projects/Bench.AutofacApiServer/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "anonymousAuthentication": true,
5 | "iisExpress": {
6 | "applicationUrl": "http://localhost:55009",
7 | "sslPort": 0
8 | },
9 | "windowsAuthentication": false
10 | },
11 | "profiles": {
12 | "Bench.AutofacApiServer": {
13 | "applicationUrl": "http://localhost:5000",
14 | "commandName": "Project",
15 | "environmentVariables": {
16 | "ASPNETCORE_ENVIRONMENT": "Development"
17 | },
18 | "launchBrowser": true,
19 | "launchUrl": "weatherforecast"
20 | },
21 | "IIS Express": {
22 | "commandName": "IISExpress",
23 | "environmentVariables": {
24 | "ASPNETCORE_ENVIRONMENT": "Development"
25 | },
26 | "launchBrowser": true,
27 | "launchUrl": "weatherforecast"
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/bench/Autofac.Extensions.DependencyInjection.Bench/Harness.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using BenchmarkDotNet.Running;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Bench;
7 |
8 | public class Harness
9 | {
10 | [Fact]
11 | public void Request() => RunBenchmark();
12 |
13 | ///
14 | /// This method is used to enforce that benchmark types are added to
15 | /// so that they can be used directly from the command line in as well.
16 | ///
17 | private static void RunBenchmark()
18 | {
19 | var targetType = typeof(TBenchmark);
20 | var benchmarkType = Benchmarks.All.Single(type => type == targetType);
21 | BenchmarkRunner.Run(benchmarkType, new BenchmarkConfig());
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/test/Integration.Net6/Startup.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Diagnostics.CodeAnalysis;
5 | using Autofac;
6 | using Microsoft.AspNetCore.Builder;
7 | using Microsoft.Extensions.DependencyInjection;
8 |
9 | namespace Integration.Net6;
10 |
11 | [SuppressMessage("CA1052", "CA1052", Justification = "Startup must not be a static class.")]
12 | public class Startup
13 | {
14 | public static void Configure(IApplicationBuilder app)
15 | {
16 | app.UseRouting()
17 | .UseEndpoints(endpoints => endpoints.MapControllers());
18 | }
19 |
20 | public static void ConfigureServices(IServiceCollection services)
21 | {
22 | services.AddMvc();
23 | }
24 |
25 | public static void ConfigureContainer(ContainerBuilder builder)
26 | {
27 | builder.RegisterType().As();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/test/Integration.Net7/Startup.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Diagnostics.CodeAnalysis;
5 | using Autofac;
6 | using Microsoft.AspNetCore.Builder;
7 | using Microsoft.Extensions.DependencyInjection;
8 |
9 | namespace Integration.Net7;
10 |
11 | [SuppressMessage("CA1052", "CA1052", Justification = "Startup must not be a static class.")]
12 | public class Startup
13 | {
14 | public static void Configure(IApplicationBuilder app)
15 | {
16 | app.UseRouting()
17 | .UseEndpoints(endpoints => endpoints.MapControllers());
18 | }
19 |
20 | public static void ConfigureServices(IServiceCollection services)
21 | {
22 | services.AddMvc();
23 | }
24 |
25 | public static void ConfigureContainer(ContainerBuilder builder)
26 | {
27 | builder.RegisterType().As();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/test/Integration.Net8/Startup.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Diagnostics.CodeAnalysis;
5 | using Autofac;
6 | using Microsoft.AspNetCore.Builder;
7 | using Microsoft.Extensions.DependencyInjection;
8 |
9 | namespace Integration.Net8;
10 |
11 | [SuppressMessage("CA1052", "CA1052", Justification = "Startup must not be a static class.")]
12 | public class Startup
13 | {
14 | public static void Configure(IApplicationBuilder app)
15 | {
16 | app.UseRouting()
17 | .UseEndpoints(endpoints => endpoints.MapControllers());
18 | }
19 |
20 | public static void ConfigureServices(IServiceCollection services)
21 | {
22 | services.AddMvc();
23 | }
24 |
25 | public static void ConfigureContainer(ContainerBuilder builder)
26 | {
27 | builder.RegisterType().As();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/bench/projects/Bench.AutofacApiServer/Services.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | // Disable the "file may only contain one type" warnings for these tiny
5 | // logic-free stubs. If they grow to hold logic, we should split them up.
6 | #pragma warning disable SA1402, SA1649
7 |
8 | namespace BenchProject.AutofacApiServer;
9 |
10 | public class A
11 | {
12 | public A(B1 b1, B2 b2)
13 | {
14 | }
15 | }
16 |
17 | public class B1
18 | {
19 | public B1(B2 b2, C1 c1, C2 c2)
20 | {
21 | }
22 | }
23 |
24 | public class B2
25 | {
26 | public B2(C1 c1, C2 c2)
27 | {
28 | }
29 | }
30 |
31 | public class C1
32 | {
33 | public C1(C2 c2, D1 d1, D2 d2)
34 | {
35 | }
36 | }
37 |
38 | public class C2
39 | {
40 | public C2(D1 d1, D2 d2)
41 | {
42 | }
43 | }
44 |
45 | public class D1
46 | {
47 | }
48 |
49 | public class D2
50 | {
51 | }
52 |
53 | #pragma warning restore SA1402, SA1649
54 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/ChildScopeFactorySpecificationTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 | using Microsoft.Extensions.DependencyInjection.Specification;
6 |
7 | namespace Autofac.Extensions.DependencyInjection.Test.Specification;
8 |
9 | public class ChildScopeFactorySpecificationTests : DependencyInjectionSpecificationTests
10 | {
11 | public override bool SupportsIServiceProviderIsService => true;
12 |
13 | protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection)
14 | {
15 | var container = new ContainerBuilder().Build();
16 | var rootScope = container.BeginLifetimeScope();
17 | var factory = new AutofacChildLifetimeScopeServiceProviderFactory(() => rootScope);
18 | return factory.CreateServiceProvider(factory.CreateBuilder(serviceCollection));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Specification/ChildScopeFactoryKeyedSpecificationTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 | using Microsoft.Extensions.DependencyInjection.Specification;
6 |
7 | namespace Autofac.Extensions.DependencyInjection.Test.Specification;
8 |
9 | public class ChildScopeFactoryKeyedSpecificationTests : KeyedDependencyInjectionSpecificationTests
10 | {
11 | public override bool SupportsIServiceProviderIsKeyedService => true;
12 |
13 | protected override IServiceProvider CreateServiceProvider(IServiceCollection collection)
14 | {
15 | var container = new ContainerBuilder().Build();
16 | var rootScope = container.BeginLifetimeScope();
17 | var factory = new AutofacChildLifetimeScopeServiceProviderFactory(() => rootScope);
18 | return factory.CreateServiceProvider(factory.CreateBuilder(collection));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.doc diff=astextplain
2 | *.DOC diff=astextplain
3 | *.docx diff=astextplain
4 | *.DOCX diff=astextplain
5 | *.dot diff=astextplain
6 | *.DOT diff=astextplain
7 | *.pdf diff=astextplain
8 | *.PDF diff=astextplain
9 | *.rtf diff=astextplain
10 | *.RTF diff=astextplain
11 |
12 | *.jpg binary
13 | *.png binary
14 | *.gif binary
15 |
16 | *.cs text=auto diff=csharp
17 | *.vb text=auto
18 | *.resx text=auto
19 | *.c text=auto
20 | *.cpp text=auto
21 | *.cxx text=auto
22 | *.h text=auto
23 | *.hxx text=auto
24 | *.py text=auto
25 | *.rb text=auto
26 | *.java text=auto
27 | *.html text=auto
28 | *.htm text=auto
29 | *.css text=auto
30 | *.scss text=auto
31 | *.sass text=auto
32 | *.less text=auto
33 | *.js text=auto
34 | *.lisp text=auto
35 | *.clj text=auto
36 | *.sql text=auto
37 | *.php text=auto
38 | *.lua text=auto
39 | *.m text=auto
40 | *.asm text=auto
41 | *.erl text=auto
42 | *.fs text=auto
43 | *.fsx text=auto
44 | *.hs text=auto
45 |
46 | *.csproj text=auto
47 | *.vbproj text=auto
48 | *.fsproj text=auto
49 | *.dbproj text=auto
50 | *.sln text=auto eol=crlf
51 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/ServiceProviderExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Test;
7 |
8 | public sealed class ServiceProviderExtensionsTests
9 | {
10 | [Fact]
11 | public void GetAutofacRootReturnsLifetimeScope()
12 | {
13 | var containerBuilder = new ContainerBuilder();
14 | containerBuilder.Populate(new ServiceCollection());
15 |
16 | var container = containerBuilder.Build();
17 | var serviceProvider = container.Resolve();
18 |
19 | Assert.NotNull(serviceProvider.GetAutofacRoot());
20 | }
21 |
22 | [Fact]
23 | public void GetAutofacRootServiceProviderNotAutofacServiceProviderThrows()
24 | => Assert.Throws(() =>
25 | new ServiceCollection().BuildServiceProvider().GetAutofacRoot());
26 | }
27 |
--------------------------------------------------------------------------------
/bench/Autofac.Extensions.DependencyInjection.Bench/BenchmarkConfig.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using BenchmarkDotNet.Configs;
5 | using BenchmarkDotNet.Diagnosers;
6 | using BenchmarkDotNet.Jobs;
7 |
8 | namespace Autofac.Extensions.DependencyInjection.Bench;
9 |
10 | internal sealed class BenchmarkConfig : ManualConfig
11 | {
12 | private const string BenchmarkArtifactsFolder = "BenchmarkDotNet.Artifacts";
13 |
14 | internal BenchmarkConfig()
15 | {
16 | Add(DefaultConfig.Instance);
17 |
18 | AddJob(Job.InProcess);
19 |
20 | var rootFolder = AppContext.BaseDirectory.Substring(0, AppContext.BaseDirectory.LastIndexOf("bin", StringComparison.OrdinalIgnoreCase));
21 | var runFolder = DateTime.Now.ToString("u").Replace(' ', '_').Replace(':', '-');
22 | ArtifactsPath = Path.Combine(rootFolder, BenchmarkArtifactsFolder, runFolder);
23 |
24 | AddDiagnoser(MemoryDiagnoser.Default);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/bench/projects/Bench.AutofacApiServer/BenchProject.AutofacApiServer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0
4 | Exe
5 | net6.0
6 | $(NoWarn);CS1591
7 | true
8 | latest
9 | ../../../build/Test.ruleset
10 | latest
11 | AllEnabledByDefault
12 | enable
13 |
14 |
15 |
16 | all
17 | runtime; build; native; contentfiles; analyzers; buildtransitive
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build and Test
2 | on:
3 | workflow_call:
4 | secrets:
5 | CODECOV_TOKEN:
6 | description: Token for uploading code coverage metrics to CodeCov.io.
7 | required: true
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - name: Checkout
13 | uses: actions/checkout@v4
14 | - name: Setup .NET
15 | uses: actions/setup-dotnet@v4
16 | with:
17 | dotnet-version: |
18 | 6.0.x
19 | 7.0.x
20 | 8.0.x
21 | - name: Build and test
22 | run: dotnet msbuild ./default.proj
23 | - name: Upload coverage
24 | uses: codecov/codecov-action@v5
25 | with:
26 | fail_ci_if_error: true
27 | files: artifacts/logs/*/coverage.cobertura.xml
28 | token: ${{ secrets.CODECOV_TOKEN }}
29 | - name: Upload package artifacts
30 | uses: actions/upload-artifact@v4
31 | with:
32 | name: packages
33 | path: |
34 | artifacts/packages/*.nupkg
35 | artifacts/packages/*.snupkg
36 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright © 2014 Autofac Project
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Integration.Test/IntegrationTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System;
5 | using System.Threading.Tasks;
6 | using Microsoft.AspNetCore.Mvc.Testing;
7 | using Xunit;
8 |
9 | #if NET8_0
10 | using Integration.Net8;
11 | #endif
12 | #if NET7_0
13 | using Integration.Net7;
14 | #endif
15 | #if NET6_0
16 | using Integration.Net6;
17 | #endif
18 |
19 | namespace Autofac.Extensions.DependencyInjection.Integration.Test;
20 |
21 | public class IntegrationTests : IClassFixture>
22 | {
23 | public IntegrationTests(WebApplicationFactory appFactory)
24 | {
25 | AppFactory = appFactory;
26 | }
27 |
28 | public WebApplicationFactory AppFactory { get; }
29 |
30 | [Fact]
31 | public async Task GetDate()
32 | {
33 | var client = AppFactory.CreateClient();
34 | var response = await client.GetAsync(new Uri("/Date", UriKind.Relative));
35 | response.EnsureSuccessStatusCode();
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Continuous Integration
2 | on:
3 | pull_request:
4 | branches:
5 | - develop
6 | - master
7 | push:
8 | branches:
9 | - develop
10 | - master
11 | - feature/*
12 | tags:
13 | - v[0-9]+.[0-9]+.[0-9]+
14 | # If multiple pushes happen quickly in succession, cancel the running build and
15 | # start a new one.
16 | concurrency:
17 | group: ${{ github.workflow }}-${{ github.ref }}
18 | cancel-in-progress: true
19 | jobs:
20 | # Linting
21 | dotnet-format:
22 | uses: ./.github/workflows/dotnet-format.yml
23 | pre-commit:
24 | uses: ./.github/workflows/pre-commit.yml
25 | # Build and test
26 | build:
27 | uses: ./.github/workflows/build.yml
28 | secrets:
29 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
30 | # Publish beta and release packages.
31 | publish:
32 | uses: ./.github/workflows/publish.yml
33 | needs:
34 | - build
35 | - dotnet-format
36 | - pre-commit
37 | if: ${{ github.ref == 'refs/heads/develop' || startsWith(github.ref, 'refs/tags/v') }}
38 | secrets:
39 | NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
40 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "cSpell.words": [
3 | "autofac",
4 | "cref",
5 | "diagnoser",
6 | "diagnosers",
7 | "inheritdoc",
8 | "langword",
9 | "paramref",
10 | "seealso",
11 | "typeparam",
12 | "unmanaged",
13 | "xunit"
14 | ],
15 | "coverage-gutters.coverageBaseDir": "artifacts/logs",
16 | "coverage-gutters.coverageFileNames": [
17 | "**/coverage.cobertura.xml"
18 | ],
19 | "dotnet.defaultSolution": "Autofac.Extensions.DependencyInjection.sln",
20 | "dotnet.preferRuntimeFromSDK": true,
21 | "dotnet.unitTestDebuggingOptions": {
22 | "enableStepFiltering": false,
23 | "justMyCode": false,
24 | "requireExactSource": false,
25 | "sourceLinkOptions": {
26 | "*": {
27 | "enabled": true
28 | }
29 | },
30 | "suppressJITOptimizations": true,
31 | "symbolOptions": {
32 | "searchNuGetOrgSymbolServer": true
33 | }
34 | },
35 | "explorer.fileNesting.enabled": true,
36 | "explorer.fileNesting.patterns": {
37 | "*.resx": "$(capture).*.resx, $(capture).designer.cs, $(capture).designer.vb"
38 | },
39 | "files.watcherExclude": {
40 | "**/target": true
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/TestCulture.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Globalization;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Test;
7 |
8 | public static class TestCulture
9 | {
10 | public static void With(CultureInfo culture, Action test)
11 | {
12 | var originalCulture = Thread.CurrentThread.CurrentCulture;
13 | var originalUICulture = Thread.CurrentThread.CurrentUICulture;
14 | Thread.CurrentThread.CurrentCulture = culture;
15 | Thread.CurrentThread.CurrentUICulture = culture;
16 | CultureInfo.CurrentCulture.ClearCachedData();
17 | CultureInfo.CurrentUICulture.ClearCachedData();
18 | try
19 | {
20 | test?.Invoke();
21 | }
22 | finally
23 | {
24 | Thread.CurrentThread.CurrentCulture = originalCulture;
25 | Thread.CurrentThread.CurrentUICulture = originalUICulture;
26 | CultureInfo.CurrentCulture.ClearCachedData();
27 | CultureInfo.CurrentUICulture.ClearCachedData();
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/test/Integration.Net6/Integration.Net6.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net6.0
4 | $(NoWarn);CS1591
5 | true
6 | ../../Autofac.snk
7 | true
8 | enable
9 | ../../build/Test.ruleset
10 | AllEnabledByDefault
11 | true
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | all
22 | runtime; build; native; contentfiles; analyzers; buildtransitive
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/test/Integration.Net7/Integration.Net7.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net7.0
4 | $(NoWarn);CS1591
5 | true
6 | ../../Autofac.snk
7 | true
8 | enable
9 | ../../build/Test.ruleset
10 | AllEnabledByDefault
11 | true
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | all
22 | runtime; build; native; contentfiles; analyzers; buildtransitive
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/test/Integration.Net8/Integration.Net8.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0
4 | $(NoWarn);CS1591
5 | true
6 | ../../Autofac.snk
7 | true
8 | enable
9 | ../../build/Test.ruleset
10 | AllEnabledByDefault
11 | true
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | all
22 | runtime; build; native; contentfiles; analyzers; buildtransitive
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish
2 | on:
3 | workflow_call:
4 | secrets:
5 | NUGET_API_KEY:
6 | description: Token for publishing packages to NuGet.
7 | required: true
8 | jobs:
9 | publish:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - name: Setup .NET
13 | uses: actions/setup-dotnet@v4
14 | with:
15 | dotnet-version: 8.0.x
16 | - name: Download package artifacts
17 | uses: actions/download-artifact@v4
18 | with:
19 | name: packages
20 | path: artifacts/packages
21 | - name: Publish to GitHub Packages
22 | run: |
23 | 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"
24 | dotnet nuget push ./artifacts/packages/*.nupkg --skip-duplicate --source github --api-key ${{ secrets.GITHUB_TOKEN }}
25 | dotnet nuget push ./artifacts/packages/*.snupkg --skip-duplicate --source github --api-key ${{ secrets.GITHUB_TOKEN }}
26 | - name: Publish to NuGet
27 | if: ${{ startsWith(github.ref, 'refs/tags/v') }}
28 | run: |
29 | dotnet nuget push ./artifacts/packages/*.nupkg --skip-duplicate --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
30 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/ServiceCollectionExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection;
7 |
8 | ///
9 | /// Extension methods on to register the .
10 | ///
11 | public static class ServiceCollectionExtensions
12 | {
13 | ///
14 | /// Adds the to the service collection. ONLY FOR PRE-ASP.NET 3.0 HOSTING. THIS WON'T WORK
15 | /// FOR ASP.NET CORE 3.0+ OR GENERIC HOSTING.
16 | ///
17 | /// The service collection to add the factory to.
18 | /// Action on a that adds component registrations to the container.
19 | /// The service collection.
20 | public static IServiceCollection AddAutofac(this IServiceCollection services, Action? configurationAction = null)
21 | {
22 | return services.AddSingleton>(new AutofacServiceProviderFactory(configurationAction));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/bench/projects/Bench.AutofacApiServer/DefaultStartup.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | namespace BenchProject.AutofacApiServer;
5 |
6 | public class DefaultStartup
7 | {
8 | public DefaultStartup(IConfiguration configuration)
9 | {
10 | Configuration = configuration;
11 | }
12 |
13 | public IConfiguration Configuration { get; }
14 |
15 | // This method gets called by the runtime. Use this method to add services to the container.
16 | public void ConfigureServices(IServiceCollection services)
17 | {
18 | services.AddControllers();
19 |
20 | services.AddTransient();
21 | services.AddTransient();
22 | services.AddTransient();
23 | services.AddTransient();
24 | services.AddTransient();
25 | services.AddTransient();
26 | services.AddTransient();
27 | }
28 |
29 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
30 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
31 | {
32 | if (env.IsDevelopment())
33 | {
34 | app.UseDeveloperExceptionPage();
35 | }
36 |
37 | app.UseRouting();
38 |
39 | app.UseAuthorization();
40 |
41 | app.UseEndpoints(endpoints =>
42 | {
43 | endpoints.MapControllers();
44 | });
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/ServiceProviderExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Globalization;
5 |
6 | namespace Autofac.Extensions.DependencyInjection;
7 |
8 | ///
9 | /// Extension methods for use with the .
10 | ///
11 | public static class ServiceProviderExtensions
12 | {
13 | ///
14 | /// Tries to cast the instance of from when possible.
15 | ///
16 | /// The instance of .
17 | /// Throws an when instance of can't be assigned to .
18 | /// Returns the instance of exposed by .
19 | public static ILifetimeScope GetAutofacRoot(this IServiceProvider serviceProvider)
20 | {
21 | if (serviceProvider is not AutofacServiceProvider autofacServiceProvider)
22 | {
23 | throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ServiceProviderExtensionsResources.WrongProviderType, serviceProvider?.GetType()));
24 | }
25 |
26 | return autofacServiceProvider.LifetimeScope;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/AutofacChildLifetimeScopeConfigurationAdapter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | namespace Autofac.Extensions.DependencyInjection;
5 |
6 | ///
7 | /// Configuration adapter for .
8 | ///
9 | public class AutofacChildLifetimeScopeConfigurationAdapter
10 | {
11 | private readonly List> _configurationActions = new();
12 |
13 | ///
14 | /// Gets the list of configuration actions to be executed on the for the child .
15 | ///
16 | public IReadOnlyList> ConfigurationActions => _configurationActions;
17 |
18 | ///
19 | /// Adds a configuration action that will be executed when the child is created.
20 | ///
21 | /// Action on a that adds component registrations to the container.
22 | /// Throws when the passed configuration-action is null.
23 | public void Add(Action configurationAction)
24 | {
25 | if (configurationAction == null)
26 | {
27 | throw new ArgumentNullException(nameof(configurationAction));
28 | }
29 |
30 | _configurationActions.Add(configurationAction);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/ServiceDescriptorExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection;
7 |
8 | ///
9 | /// Extensions for working with .
10 | ///
11 | internal static class ServiceDescriptorExtensions
12 | {
13 | ///
14 | /// Normalizes the implementation instance data between keyed and not keyed services.
15 | ///
16 | ///
17 | /// The to normalize.
18 | ///
19 | ///
20 | /// The appropriate implementation instance from the service descriptor.
21 | ///
22 | public static object? NormalizedImplementationInstance(this ServiceDescriptor descriptor) => descriptor.IsKeyedService ? descriptor.KeyedImplementationInstance : descriptor.ImplementationInstance;
23 |
24 | ///
25 | /// Normalizes the implementation type data between keyed and not keyed services.
26 | ///
27 | ///
28 | /// The to normalize.
29 | ///
30 | ///
31 | /// The appropriate implementation type from the service descriptor.
32 | ///
33 | public static Type? NormalizedImplementationType(this ServiceDescriptor descriptor) => descriptor.IsKeyedService ? descriptor.KeyedImplementationType : descriptor.ImplementationType;
34 | }
35 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/AutofacServiceScopeFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection;
7 |
8 | ///
9 | /// Autofac implementation of the ASP.NET Core .
10 | ///
11 | ///
12 | internal class AutofacServiceScopeFactory : IServiceScopeFactory
13 | {
14 | private readonly ILifetimeScope _lifetimeScope;
15 |
16 | ///
17 | /// Initializes a new instance of the class.
18 | ///
19 | /// The lifetime scope.
20 | public AutofacServiceScopeFactory(ILifetimeScope lifetimeScope)
21 | {
22 | _lifetimeScope = lifetimeScope;
23 | }
24 |
25 | ///
26 | /// Creates an which contains an
27 | /// used to resolve dependencies within
28 | /// the scope.
29 | ///
30 | ///
31 | /// An controlling the lifetime of the scope. Once
32 | /// this is disposed, any scoped services that have been resolved
33 | /// from the
34 | /// will also be disposed.
35 | ///
36 | public IServiceScope CreateScope()
37 | {
38 | return new AutofacServiceScope(_lifetimeScope.BeginLifetimeScope());
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/ServiceCollectionExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Test;
7 |
8 | public sealed class ServiceCollectionExtensionsTests
9 | {
10 | [Fact]
11 | public void AddAutofacReturnsProvidedServiceCollection()
12 | {
13 | var collection = new ServiceCollection();
14 |
15 | var returnedCollection = collection.AddAutofac();
16 |
17 | Assert.Same(collection, returnedCollection);
18 | }
19 |
20 | [Fact]
21 | public void AddAutofacAddsAutofacServiceProviderFactoryToCollection()
22 | {
23 | var collection = new ServiceCollection();
24 |
25 | collection.AddAutofac();
26 |
27 | var service = collection.FirstOrDefault(s => s.ServiceType == typeof(IServiceProviderFactory));
28 | Assert.NotNull(service);
29 | Assert.Equal(ServiceLifetime.Singleton, service.Lifetime);
30 | }
31 |
32 | [Fact]
33 | public void AddAutofacPassesConfigurationActionToAutofacServiceProviderFactory()
34 | {
35 | var collection = new ServiceCollection();
36 |
37 | collection.AddAutofac(config => config.Register(c => "Foo"));
38 |
39 | var serviceProvider = collection.BuildServiceProvider();
40 | var factory = (IServiceProviderFactory)serviceProvider.GetService(typeof(IServiceProviderFactory));
41 | var builder = factory.CreateBuilder(collection);
42 | Assert.Equal("Foo", builder.Build().Resolve());
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Assertions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Autofac.Core;
5 |
6 | namespace Autofac.Extensions.DependencyInjection.Test;
7 |
8 | internal static class Assertions
9 | {
10 | public static void AssertRegistered(this IComponentContext context)
11 | {
12 | Assert.True(context.IsRegistered());
13 | }
14 |
15 | public static void AssertNotRegistered(this IComponentContext context)
16 | {
17 | Assert.False(context.IsRegistered());
18 | }
19 |
20 | public static void AssertImplementation(this IComponentContext context)
21 | {
22 | var service = context.Resolve();
23 | Assert.IsAssignableFrom(service);
24 | }
25 |
26 | public static void AssertSharing(this IComponentContext context, InstanceSharing sharing)
27 | {
28 | var cr = context.RegistrationFor();
29 | Assert.Equal(sharing, cr.Sharing);
30 | }
31 |
32 | public static void AssertLifetime(this IComponentContext context)
33 | {
34 | var cr = context.RegistrationFor();
35 | Assert.IsType(cr.Lifetime);
36 | }
37 |
38 | public static void AssertOwnership(this IComponentContext context, InstanceOwnership ownership)
39 | {
40 | var cr = context.RegistrationFor();
41 | Assert.Equal(ownership, cr.Ownership);
42 | }
43 |
44 | public static IComponentRegistration RegistrationFor(this IComponentContext context)
45 | {
46 | Assert.True(context.ComponentRegistry.TryGetRegistration(new TypedService(typeof(TService)), out IComponentRegistration r));
47 | return r;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "configurations": [
3 | {
4 | "args": [
5 | ],
6 | "cwd": "${workspaceFolder}/test/Integration.Net6",
7 | "env": {
8 | "ASPNETCORE_ENVIRONMENT": "Development"
9 | },
10 | "name": "Launch .NET 6 Integration Site",
11 | "preLaunchTask": "build",
12 | "program": "${workspaceFolder}/test/Integration.Net6/bin/Debug/net6.0/Integration.Net6.dll",
13 | "request": "launch",
14 | "serverReadyAction": {
15 | "action": "openExternally",
16 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)",
17 | "uriFormat": "%s/date"
18 | },
19 | "stopAtEntry": false,
20 | "type": "coreclr"
21 | },
22 | {
23 | "args": [
24 | ],
25 | "cwd": "${workspaceFolder}/test/Integration.Net7",
26 | "env": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | },
29 | "name": "Launch .NET 7 Integration Site",
30 | "preLaunchTask": "build",
31 | "program": "${workspaceFolder}/test/Integration.Net7/bin/Debug/net7.0/Integration.Net7.dll",
32 | "request": "launch",
33 | "serverReadyAction": {
34 | "action": "openExternally",
35 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)",
36 | "uriFormat": "%s/date"
37 | },
38 | "stopAtEntry": false,
39 | "type": "coreclr"
40 | },
41 | {
42 | "args": [
43 | ],
44 | "cwd": "${workspaceFolder}/test/Integration.Net8",
45 | "env": {
46 | "ASPNETCORE_ENVIRONMENT": "Development"
47 | },
48 | "name": "Launch .NET 8 Integration Site",
49 | "preLaunchTask": "build",
50 | "program": "${workspaceFolder}/test/Integration.Net8/bin/Debug/net8.0/Integration.Net8.dll",
51 | "request": "launch",
52 | "serverReadyAction": {
53 | "action": "openExternally",
54 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)",
55 | "uriFormat": "%s/date"
56 | },
57 | "stopAtEntry": false,
58 | "type": "coreclr"
59 | }
60 | ],
61 | "version": "0.2.0"
62 | }
63 |
--------------------------------------------------------------------------------
/bench/Autofac.Extensions.DependencyInjection.Bench/RequestBenchmark.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Diagnostics.CodeAnalysis;
5 | using System.Net;
6 | using BenchProject.AutofacApiServer;
7 | using Microsoft.AspNetCore.Mvc.Testing;
8 |
9 | namespace Autofac.Extensions.DependencyInjection.Bench;
10 |
11 | [SuppressMessage("CA1001", "CA1001", Justification = "Benchmark disposal happens in a global cleanup method.")]
12 | public class RequestBenchmark
13 | {
14 | private static readonly Uri ValuesUri = new("/api/values", UriKind.Relative);
15 | private WebApplicationFactory _defaultFactory;
16 | private WebApplicationFactory _autofacFactory;
17 | private HttpClient _defaultClient;
18 | private HttpClient _autofacClient;
19 |
20 | [GlobalSetup]
21 | public void Setup()
22 | {
23 | _defaultFactory = new WebApplicationFactory();
24 | _autofacFactory = new AutofacWebApplicationFactory();
25 |
26 | _defaultClient = _defaultFactory.CreateClient();
27 | _autofacClient = _autofacFactory.CreateClient();
28 | }
29 |
30 | [Benchmark(Baseline = true)]
31 | public async Task RequestDefaultDI()
32 | {
33 | var response = await _defaultClient.GetAsync(ValuesUri).ConfigureAwait(false);
34 |
35 | if (response.StatusCode != HttpStatusCode.OK)
36 | {
37 | throw new HttpRequestException();
38 | }
39 | }
40 |
41 | [Benchmark]
42 | public async Task RequestAutofacDI()
43 | {
44 | var response = await _autofacClient.GetAsync(ValuesUri).ConfigureAwait(false);
45 |
46 | if (response.StatusCode != HttpStatusCode.OK)
47 | {
48 | throw new HttpRequestException();
49 | }
50 | }
51 |
52 | [GlobalCleanup]
53 | public void Cleanup()
54 | {
55 | _defaultFactory.Dispose();
56 | _autofacFactory.Dispose();
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "linux": {
3 | "options": {
4 | "shell": {
5 | "args": [
6 | "-NoProfile",
7 | "-Command"
8 | ],
9 | "executable": "pwsh"
10 | }
11 | }
12 | },
13 | "osx": {
14 | "options": {
15 | "shell": {
16 | "args": [
17 | "-NoProfile",
18 | "-Command"
19 | ],
20 | "executable": "/usr/local/bin/pwsh"
21 | }
22 | }
23 | },
24 | "tasks": [
25 | {
26 | "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",
27 | "label": "create log directory",
28 | "type": "shell"
29 | },
30 | {
31 | "args": [
32 | "build",
33 | "${workspaceFolder}/Autofac.Extensions.DependencyInjection.sln",
34 | "/property:GenerateFullPaths=true",
35 | "/consoleloggerparameters:NoSummary"
36 | ],
37 | "command": "dotnet",
38 | "group": {
39 | "isDefault": true,
40 | "kind": "build"
41 | },
42 | "label": "build",
43 | "problemMatcher": "$msCompile",
44 | "type": "shell"
45 | },
46 | {
47 | "args": [
48 | "test",
49 | "${workspaceFolder}/Autofac.Extensions.DependencyInjection.sln",
50 | "/property:GenerateFullPaths=true",
51 | "/consoleloggerparameters:NoSummary",
52 | "--results-directory",
53 | "\"artifacts/logs\"",
54 | "--logger:trx",
55 | "--collect:\"XPlat Code Coverage\"",
56 | "--settings:build/Coverage.runsettings",
57 | "--filter",
58 | "FullyQualifiedName!~Bench"
59 | ],
60 | "command": "dotnet",
61 | "dependsOn": [
62 | "create log directory"
63 | ],
64 | "group": {
65 | "isDefault": true,
66 | "kind": "test"
67 | },
68 | "label": "test",
69 | "problemMatcher": "$msCompile",
70 | "type": "process"
71 | }
72 | ],
73 | "version": "2.0.0",
74 | "windows": {
75 | "options": {
76 | "shell": {
77 | "args": [
78 | "-NoProfile",
79 | "-ExecutionPolicy",
80 | "Bypass",
81 | "-Command"
82 | ],
83 | "executable": "pwsh.exe"
84 | }
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/Autofac.Extensions.DependencyInjection.Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0;net7.0;net6.0
4 | $(NoWarn);CS1591
5 | true
6 | ../../Autofac.snk
7 | true
8 | true
9 | ../../build/Test.ruleset
10 | AllEnabledByDefault
11 | true
12 | false
13 | latest
14 | enable
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | all
28 | runtime; build; native; contentfiles; analyzers; buildtransitive
29 |
30 |
31 |
32 |
33 |
34 |
35 | all
36 | runtime; build; native; contentfiles; analyzers; buildtransitive
37 |
38 |
39 |
40 | all
41 | runtime; build; native; contentfiles; analyzers
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/bench/Autofac.Extensions.DependencyInjection.Bench/Autofac.Extensions.DependencyInjection.Bench.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0
4 | $(NoWarn);CS1591
5 | Exe
6 | false
7 | $([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)
8 | true
9 | true
10 | true
11 | ../../build/Test.ruleset
12 | AllEnabledByDefault
13 | true
14 | false
15 | enable
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | all
32 | runtime; build; native; contentfiles; analyzers; buildtransitive
33 |
34 |
35 |
36 | all
37 | runtime; build; native; contentfiles; analyzers
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Integration.Test/Autofac.Extensions.DependencyInjection.Integration.Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0;net7.0;net6.0
4 | $(NoWarn);CS1591
5 | true
6 | ../../Autofac.snk
7 | true
8 | true
9 | ../../build/Test.ruleset
10 | AllEnabledByDefault
11 | true
12 | false
13 | latest
14 | enable
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 | all
39 | runtime; build; native; contentfiles; analyzers; buildtransitive
40 |
41 |
42 |
43 | all
44 | runtime; build; native; contentfiles; analyzers
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/AutofacServiceScope.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection;
7 |
8 | ///
9 | /// Autofac implementation of the ASP.NET Core .
10 | ///
11 | ///
12 | internal class AutofacServiceScope : IServiceScope, IAsyncDisposable
13 | {
14 | private readonly AutofacServiceProvider _serviceProvider;
15 | private bool _disposed;
16 |
17 | ///
18 | /// Initializes a new instance of the class.
19 | ///
20 | ///
21 | /// The lifetime scope from which services should be resolved for this service scope.
22 | ///
23 | public AutofacServiceScope(ILifetimeScope lifetimeScope)
24 | {
25 | _serviceProvider = new AutofacServiceProvider(lifetimeScope);
26 | }
27 |
28 | ///
29 | /// Gets an corresponding to this service scope.
30 | ///
31 | ///
32 | /// An that can be used to resolve dependencies from the scope.
33 | ///
34 | public IServiceProvider ServiceProvider
35 | {
36 | get
37 | {
38 | return _serviceProvider;
39 | }
40 | }
41 |
42 | ///
43 | /// Disposes of the lifetime scope and resolved disposable services.
44 | ///
45 | public void Dispose()
46 | {
47 | Dispose(true);
48 | GC.SuppressFinalize(this);
49 | }
50 |
51 | ///
52 | public async ValueTask DisposeAsync()
53 | {
54 | if (!_disposed)
55 | {
56 | _disposed = true;
57 | await _serviceProvider.DisposeAsync().ConfigureAwait(false);
58 | }
59 | }
60 |
61 | ///
62 | /// Releases unmanaged and - optionally - managed resources.
63 | ///
64 | ///
65 | /// to release both managed and unmanaged resources; to release only unmanaged resources.
66 | ///
67 | protected virtual void Dispose(bool disposing)
68 | {
69 | if (!_disposed)
70 | {
71 | _disposed = true;
72 |
73 | if (disposing)
74 | {
75 | _serviceProvider.Dispose();
76 | }
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/FromKeyedServicesAttributeExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Reflection;
5 | using Microsoft.Extensions.DependencyInjection;
6 |
7 | namespace Autofac.Extensions.DependencyInjection;
8 |
9 | ///
10 | /// Extensions for working with .
11 | ///
12 | internal static class FromKeyedServicesAttributeExtensions
13 | {
14 | ///
15 | /// Resolves a constructor parameter based on keyed service requirements.
16 | ///
17 | /// The attribute marking the keyed service dependency in a constructor.
18 | /// The specific parameter being resolved that is marked with this attribute.
19 | /// The component context under which the parameter is being resolved.
20 | ///
21 | /// The instance of the object that should be used for the parameter value.
22 | ///
23 | ///
24 | /// Thrown if or is .
25 | ///
26 | public static object? ResolveParameter(this FromKeyedServicesAttribute attribute, ParameterInfo parameter, IComponentContext context)
27 | {
28 | // Adapter for FromKeyedServicesAttribute to work like Autofac.Features.AttributeFilters.KeyFilterAttribute.
29 | context.TryResolveKeyed(attribute.Key, parameter.ParameterType, out var value);
30 | return value;
31 | }
32 |
33 | ///
34 | /// Checks a constructor parameter can be resolved based on keyed service requirements.
35 | ///
36 | /// The attribute marking the keyed service dependency in a constructor.
37 | /// The specific parameter being resolved that is marked with this attribute.
38 | /// The component context under which the parameter is being resolved.
39 | /// true if parameter can be resolved; otherwise, false.
40 | public static bool CanResolveParameter(this FromKeyedServicesAttribute attribute, ParameterInfo parameter, IComponentContext context)
41 | {
42 | // Adapter for FromKeyedServicesAttribute to work like Autofac.Features.AttributeFilters.KeyFilterAttribute.
43 | return context.ComponentRegistry.IsRegistered(new Autofac.Core.KeyedService(attribute.Key, parameter.ParameterType));
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/AutofacServiceProviderFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Autofac.Builder;
5 | using Microsoft.Extensions.DependencyInjection;
6 |
7 | namespace Autofac.Extensions.DependencyInjection;
8 |
9 | ///
10 | /// A factory for creating a and an .
11 | ///
12 | public class AutofacServiceProviderFactory : IServiceProviderFactory
13 | {
14 | private readonly Action _configurationAction;
15 | private readonly ContainerBuildOptions _containerBuildOptions = ContainerBuildOptions.None;
16 |
17 | ///
18 | /// Initializes a new instance of the class.
19 | ///
20 | /// The container options to use when building the container.
21 | /// Action on a that adds component registrations to the container.
22 | public AutofacServiceProviderFactory(
23 | ContainerBuildOptions containerBuildOptions,
24 | Action? configurationAction = null)
25 | : this(configurationAction) =>
26 | _containerBuildOptions = containerBuildOptions;
27 |
28 | ///
29 | /// Initializes a new instance of the class.
30 | ///
31 | /// Action on a that adds component registrations to the container..
32 | public AutofacServiceProviderFactory(Action? configurationAction = null) =>
33 | _configurationAction = configurationAction ?? (builder => { });
34 |
35 | ///
36 | /// Creates a container builder from an .
37 | ///
38 | /// The collection of services.
39 | /// A container builder that can be used to create an .
40 | public ContainerBuilder CreateBuilder(IServiceCollection services)
41 | {
42 | var builder = new ContainerBuilder();
43 |
44 | builder.Populate(services);
45 |
46 | _configurationAction(builder);
47 |
48 | return builder;
49 | }
50 |
51 | ///
52 | /// Creates an from the container builder.
53 | ///
54 | /// The container builder.
55 | /// An .
56 | public IServiceProvider CreateServiceProvider(ContainerBuilder containerBuilder)
57 | {
58 | if (containerBuilder == null)
59 | {
60 | throw new ArgumentNullException(nameof(containerBuilder));
61 | }
62 |
63 | var container = containerBuilder.Build(_containerBuildOptions);
64 |
65 | return new AutofacServiceProvider(container);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # Project specific files
5 | artifacts/
6 | BenchmarkDotNet.Artifacts/
7 |
8 | # User-specific files
9 | *.suo
10 | *.user
11 | *.sln.docstates
12 | *.ide
13 | Index.dat
14 | Storage.dat
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Rr]elease/
19 | x64/
20 | [Bb]in/
21 | [Oo]bj/
22 |
23 | # Visual Studio 2015 cache/options directory
24 | .dotnet/
25 | .vs/
26 | .cr/
27 |
28 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
29 | !packages/*/build/
30 |
31 | # MSTest test Results
32 | [Tt]est[Rr]esult*/
33 | [Bb]uild[Ll]og.*
34 | *.TestResults.xml
35 | results/
36 |
37 | *_i.c
38 | *_p.c
39 | *.ilk
40 | *.meta
41 | *.obj
42 | *.pch
43 | *.pdb
44 | *.pgc
45 | *.pgd
46 | *.rsp
47 | *.sbr
48 | *.tlb
49 | *.tli
50 | *.tlh
51 | *.tmp
52 | *.tmp_proj
53 | *.log
54 | *.vspscc
55 | *.vssscc
56 | .builds
57 | *.pidb
58 | *.log
59 | *.scc
60 |
61 | # Visual C++ cache files
62 | ipch/
63 | *.aps
64 | *.ncb
65 | *.opensdf
66 | *.sdf
67 | *.cachefile
68 |
69 | # Visual Studio profiler
70 | *.psess
71 | *.vsp
72 | *.vspx
73 |
74 | # Guidance Automation Toolkit
75 | *.gpState
76 |
77 | # ReSharper is a .NET coding add-in
78 | _ReSharper*/
79 | *.[Rr]e[Ss]harper
80 |
81 | # TeamCity is a build add-in
82 | _TeamCity*
83 |
84 | # DotCover is a Code Coverage Tool
85 | *.dotCover
86 |
87 | # NCrunch
88 | *.ncrunch*
89 | .*crunch*.local.xml
90 |
91 | # Installshield output folder
92 | [Ee]xpress/
93 |
94 | # DocProject is a documentation generator add-in
95 | DocProject/buildhelp/
96 | DocProject/Help/*.HxT
97 | DocProject/Help/*.HxC
98 | DocProject/Help/*.hhc
99 | DocProject/Help/*.hhk
100 | DocProject/Help/*.hhp
101 | DocProject/Help/Html2
102 | DocProject/Help/html
103 |
104 | # Click-Once directory
105 | publish/
106 |
107 | # Publish Web Output
108 | *.[Pp]ublish.xml
109 | *.pubxml
110 |
111 | # NuGet Packages Directory
112 | packages/
113 |
114 | # Windows Azure Build Output
115 | csx
116 | *.build.csdef
117 |
118 | # Windows Store app package directory
119 | AppPackages/
120 |
121 | # Others
122 | sql/
123 | *.Cache
124 | ClientBin/
125 | [Ss]tyle[Cc]op.*
126 | !stylecop.json
127 | ~$*
128 | *~
129 | *.dbmdl
130 | *.pfx
131 | *.publishsettings
132 | node_modules/
133 | bower_components/
134 | wwwroot/
135 | project.lock.json
136 | *.Designer.cs
137 |
138 | # RIA/Silverlight projects
139 | Generated_Code/
140 |
141 | # Backup & report files from converting an old project file to a newer
142 | # Visual Studio version. Backup files are not needed, because we have git ;-)
143 | _UpgradeReport_Files/
144 | Backup*/
145 | UpgradeLog*.XML
146 | UpgradeLog*.htm
147 |
148 | # SQL Server files
149 | App_Data/*.mdf
150 | App_Data/*.ldf
151 |
152 | # =========================
153 | # Windows detritus
154 | # =========================
155 |
156 | # Windows image file caches
157 | Thumbs.db
158 | ehthumbs.db
159 |
160 | # Folder config file
161 | Desktop.ini
162 |
163 | # Recycle Bin used on file shares
164 | $RECYCLE.BIN/
165 |
166 | # Mac crap
167 | .DS_Store
168 |
169 | # JetBrains Rider
170 | .idea
171 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/AutofacChildLifetimeScopeServiceProviderFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Microsoft.Extensions.DependencyInjection;
5 |
6 | namespace Autofac.Extensions.DependencyInjection;
7 |
8 | ///
9 | /// A factory for creating a that wraps a child created from an existing parent .
10 | ///
11 | public class AutofacChildLifetimeScopeServiceProviderFactory : IServiceProviderFactory
12 | {
13 | private static readonly Action FallbackConfigurationAction = builder => { };
14 | private readonly Action _containerConfigurationAction;
15 | private readonly ILifetimeScope _rootLifetimeScope;
16 |
17 | ///
18 | /// Initializes a new instance of the class.
19 | ///
20 | /// A function to retrieve the root instance.
21 | /// Action on a that adds component registrations to the container.
22 | public AutofacChildLifetimeScopeServiceProviderFactory(Func rootLifetimeScopeAccessor, Action? configurationAction = null)
23 | {
24 | if (rootLifetimeScopeAccessor == null)
25 | {
26 | throw new ArgumentNullException(nameof(rootLifetimeScopeAccessor));
27 | }
28 |
29 | _rootLifetimeScope = rootLifetimeScopeAccessor();
30 | _containerConfigurationAction = configurationAction ?? FallbackConfigurationAction;
31 | }
32 |
33 | ///
34 | /// Initializes a new instance of the class.
35 | ///
36 | /// The root instance.
37 | /// Action on a that adds component registrations to the container.
38 | public AutofacChildLifetimeScopeServiceProviderFactory(ILifetimeScope rootLifetimeScope, Action? configurationAction = null)
39 | {
40 | _rootLifetimeScope = rootLifetimeScope ?? throw new ArgumentNullException(nameof(rootLifetimeScope));
41 | _containerConfigurationAction = configurationAction ?? FallbackConfigurationAction;
42 | }
43 |
44 | ///
45 | /// Creates a container builder from an .
46 | ///
47 | /// The collection of services.
48 | /// A container builder that can be used to create an .
49 | public AutofacChildLifetimeScopeConfigurationAdapter CreateBuilder(IServiceCollection services)
50 | {
51 | var actions = new AutofacChildLifetimeScopeConfigurationAdapter();
52 |
53 | actions.Add(builder => builder.Populate(services));
54 | actions.Add(builder => _containerConfigurationAction(builder));
55 |
56 | return actions;
57 | }
58 |
59 | ///
60 | /// Creates an from the container builder.
61 | ///
62 | /// The adapter holding configuration applied to creating the .
63 | /// An .
64 | public IServiceProvider CreateServiceProvider(AutofacChildLifetimeScopeConfigurationAdapter containerBuilder)
65 | {
66 | if (containerBuilder == null)
67 | {
68 | throw new ArgumentNullException(nameof(containerBuilder));
69 | }
70 |
71 | var scope = _rootLifetimeScope.BeginLifetimeScope(scopeBuilder =>
72 | {
73 | foreach (var action in containerBuilder.ConfigurationActions)
74 | {
75 | action(scopeBuilder);
76 | }
77 | });
78 |
79 | return new AutofacServiceProvider(scope);
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/KeyedServiceMiddleware.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using System.Reflection;
5 | using Autofac.Core;
6 | using Autofac.Core.Resolving.Pipeline;
7 | using Microsoft.Extensions.DependencyInjection;
8 |
9 | namespace Autofac.Extensions.DependencyInjection;
10 |
11 | ///
12 | /// Middleware that supports keyed service compatibility.
13 | ///
14 | internal class KeyedServiceMiddleware : IResolveMiddleware
15 | {
16 | // [FromKeyedServices("key")] - Specifies a keyed service
17 | // for injection into a constructor. This is similar to the
18 | // Autofac [KeyFilter] attribute.
19 | private static readonly Parameter FromKeyedServicesParameter = new ResolvedParameter(
20 | (p, c) =>
21 | {
22 | var filter = p.GetCustomAttributes(true).FirstOrDefault();
23 | return filter is not null && filter.CanResolveParameter(p, c);
24 | },
25 | (p, c) =>
26 | {
27 | var filter = p.GetCustomAttributes(true).First();
28 | return filter.ResolveParameter(p, c);
29 | });
30 |
31 | private readonly bool _addFromKeyedServiceParameter;
32 |
33 | ///
34 | /// Initializes a new instance of the class.
35 | ///
36 | /// Whether or not the from-keyed-service parameter should be added.
37 | public KeyedServiceMiddleware(bool addFromKeyedServiceParameter)
38 | {
39 | _addFromKeyedServiceParameter = addFromKeyedServiceParameter;
40 | }
41 |
42 | ///
43 | /// Gets a single instance of this middleware that does not add the keyed services parameter.
44 | ///
45 | public static KeyedServiceMiddleware InstanceWithoutFromKeyedServicesParameter { get; } = new(addFromKeyedServiceParameter: false);
46 |
47 | ///
48 | /// Gets a single instance of this middleware that adds the keyed services parameter.
49 | ///
50 | public static KeyedServiceMiddleware InstanceWithFromKeyedServicesParameter { get; } = new(addFromKeyedServiceParameter: true);
51 |
52 | ///
53 | public PipelinePhase Phase => PipelinePhase.Activation;
54 |
55 | ///
56 | public void Execute(ResolveRequestContext context, Action next)
57 | {
58 | List? newParameters = null;
59 |
60 | if (context.Service is Autofac.Core.KeyedService keyedService)
61 | {
62 | newParameters = new List(context.Parameters);
63 |
64 | var key = keyedService.ServiceKey;
65 |
66 | // [ServiceKey] - indicates that the parameter value should
67 | // be the service key used during resolution.
68 | newParameters.Add(new ResolvedParameter(
69 | (p, c) =>
70 | {
71 | return p.GetCustomAttributes(true).FirstOrDefault() is not null;
72 | },
73 | (p, c) =>
74 | {
75 | // If the key is an object but the constructor takes
76 | // a string, we need to safely convert that. This is
77 | // particularly interesting in the AnyKey scenario.
78 | return KeyTypeManipulation.ChangeToCompatibleType(key, p.ParameterType, p);
79 | }));
80 | }
81 |
82 | if (_addFromKeyedServiceParameter)
83 | {
84 | newParameters ??= new List(context.Parameters);
85 |
86 | // [FromKeyedServices("key")] - Specifies a keyed service
87 | // for injection into a constructor. This is similar to the
88 | // Autofac [KeyFilter] attribute.
89 | newParameters.Add(FromKeyedServicesParameter);
90 | }
91 |
92 | if (newParameters is not null)
93 | {
94 | context.ChangeParameters(newParameters);
95 | }
96 |
97 | next(context);
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/default.proj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 10.0.1
6 | Autofac.Extensions.DependencyInjection
7 | Release
8 | $([System.IO.Path]::Combine($(MSBuildProjectDirectory),"artifacts"))
9 | $([System.IO.Path]::Combine($(ArtifactDirectory),"packages"))
10 | $([System.IO.Path]::Combine($(ArtifactDirectory),"logs"))
11 | $([System.IO.Path]::Combine($(MSBuildProjectDirectory),'build/Coverage.runsettings'))
12 | $([System.DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssZ'))
13 |
14 |
15 |
16 |
17 | $(Version)-local
18 |
19 |
20 |
21 |
22 | $(Version)
23 |
24 |
25 |
26 |
27 | $(Version)-beta$(BuildDateTime)
28 |
29 |
30 |
31 |
32 | $(Version)-alpha$(BuildDateTime)
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/src/Autofac.Extensions.DependencyInjection/Autofac.Extensions.DependencyInjection.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Autofac.Extensions.DependencyInjection
5 | Autofac.Extensions.DependencyInjection
6 | Autofac implementation of the interfaces in Microsoft.Extensions.DependencyInjection.Abstractions, the .NET Framework dependency injection abstraction.
7 | Copyright © 2015 Autofac Contributors
8 | Autofac Contributors
9 | Autofac
10 | Autofac
11 | ../../Autofac.snk
12 | true
13 | en-US
14 |
15 | net8.0;net7.0;net6.0;netstandard2.1;netstandard2.0
16 | latest
17 | enable
18 | true
19 | ../../build/Source.ruleset
20 | true
21 | AllEnabledByDefault
22 | enable
23 |
24 | Autofac.Extensions.DependencyInjection
25 | autofac;di;ioc;dependencyinjection;aspnet;aspnetcore
26 | Release notes are at https://github.com/autofac/Autofac.Extensions.DependencyInjection/releases
27 | icon.png
28 | https://autofac.org
29 | MIT
30 | README.md
31 | git
32 | https://github.com/autofac/Autofac.Extensions.DependencyInjection
33 | true
34 | true
35 | true
36 | true
37 | snupkg
38 |
39 | PrepareResources;$(CompileDependsOn)
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 | all
55 |
56 |
57 | all
58 |
59 |
60 |
61 |
62 |
63 | MSBuild:Compile
64 | CSharp
65 | $(IntermediateOutputPath)%(Filename).Designer.cs
66 | %(Filename)
67 |
68 |
69 |
70 |
71 | Autofac.Extensions.DependencyInjection
72 |
73 |
74 | Autofac.Extensions.DependencyInjection
75 |
76 |
77 | Autofac.Extensions.DependencyInjection
78 |
79 |
80 |
81 |
--------------------------------------------------------------------------------
/test/Autofac.Extensions.DependencyInjection.Test/AutofacServiceProviderFactoryTests.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Autofac Project. All rights reserved.
2 | // Licensed under the MIT License. See LICENSE in the project root for license information.
3 |
4 | using Autofac.Builder;
5 | using Microsoft.Extensions.DependencyInjection;
6 |
7 | namespace Autofac.Extensions.DependencyInjection.Test;
8 |
9 | public class AutofacServiceProviderFactoryTests
10 | {
11 | [Fact]
12 | public void CreateBuilderReturnsNewInstance()
13 | {
14 | var factory = new AutofacServiceProviderFactory();
15 |
16 | var builder = factory.CreateBuilder(new ServiceCollection());
17 |
18 | Assert.NotNull(builder);
19 | }
20 |
21 | [Fact]
22 | public void CreateBuilderExecutesConfigurationActionWhenProvided()
23 | {
24 | var factory = new AutofacServiceProviderFactory(config => config.Register(c => "Foo"));
25 |
26 | var builder = factory.CreateBuilder(new ServiceCollection());
27 |
28 | Assert.Equal("Foo", builder.Build().Resolve());
29 | }
30 |
31 | [Fact]
32 | public void CreateBuilderAllowsForNullConfigurationAction()
33 | {
34 | var factory = new AutofacServiceProviderFactory();
35 |
36 | var builder = factory.CreateBuilder(new ServiceCollection());
37 |
38 | Assert.NotNull(builder);
39 | }
40 |
41 | [Fact]
42 | public void CreateBuilderReturnsInstanceWithServicesPopulated()
43 | {
44 | var factory = new AutofacServiceProviderFactory();
45 | var services = new ServiceCollection();
46 | services.AddTransient