diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index b3f329f..b3a41fc 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,33 +1,33 @@ name: Deploy on: push: - branches: [ master ] + branches: [ master ] jobs: test: - runs-on: windows-latest + runs-on: ubuntu-latest steps: - name: Checkout Sources - uses: actions/checkout@v2 + uses: actions/checkout@v6 with: fetch-depth: 0 - - name: Setup .NET 8 - uses: actions/setup-dotnet@v4 + - name: Setup .NET 10 + uses: actions/setup-dotnet@v5 with: - dotnet-version: 8.0.x + dotnet-version: 10.0.x - name: "Build and Test" run: | dotnet build dotnet test version: needs: test - runs-on: windows-latest - outputs: + runs-on: ubuntu-latest + outputs: version: ${{ steps.newversion.outputs.version }} - tag: ${{ steps.newversion.outputs.tag }} + tag: ${{ steps.newversion.outputs.tag }} steps: - name: Checkout Sources - uses: actions/checkout@v2 + uses: actions/checkout@v6 with: fetch-depth: 0 - name: Set New Version @@ -36,22 +36,17 @@ jobs: run: | $currentVersion = git describe --abbrev=0 --tags --match "v[0-9]*.[0-9]*.[0-9]*-Release" - if ($currentVersion) { + if ($currentVersion -ne $null) { $v = $currentVersion.Split('-')[0].TrimStart('v') Write-Output "RELEASE: New Version: $($v)" Write-Output "version=$($v)" >> $Env:GITHUB_OUTPUT Write-Output "tag=$($currentVersion)" >> $Env:GITHUB_OUTPUT } else { - + $currentVersion = git describe --abbrev=0 --tags --match "v[0-9]*.[0-9]*.[0-9]*" - $currentVersion = git describe --match "$($currentVersion)" --long $versionParts = $currentVersion.Split('-') $v = $versionParts[0] - $increment = [int]$versionParts[1] - - if ($increment -gt 0) { - $increment = 1 - } + $increment = 1 $vparts = $v.Split('.') $vparts[2] = "$([int]$vparts[2] + [int]$increment)" @@ -63,20 +58,20 @@ jobs: } prepublish: needs: [test, version] - runs-on: windows-latest + runs-on: ubuntu-latest outputs: description: ${{ steps.meta.outputs.description }} changeinfo: ${{ steps.meta.outputs.changeinfo }} steps: - name: Checkout Sources - uses: actions/checkout@v2 + uses: actions/checkout@v6 with: fetch-depth: 0 - name : Get Meta Data shell: pwsh id: meta run: | - [xml]$xml = get-content "src/Autofac.EasyPropInject.csproj" + [xml]$xml = get-content "src/Autofac.EasyPropInject.csproj" $description = $xml.SelectSingleNode("//Description").InnerText; $changes = $xml.SelectSingleNode("//PackageReleaseNotes").InnerText; Write-Output "description=$($description.Trim().Replace("`t", '') | ConvertTo-Json)" >> $Env:GITHUB_OUTPUT @@ -84,28 +79,27 @@ jobs: publish: needs: [test, version, prepublish] - runs-on: windows-latest + runs-on: ubuntu-latest + permissions: + contents: write steps: - - name: Setup .NET 8 - uses: actions/setup-dotnet@v4 + - name: Setup .NET 10 + uses: actions/setup-dotnet@v5 with: - dotnet-version: 8.0.x + dotnet-version: 10.0.x - name: Checkout Sources - uses: actions/checkout@v2 + uses: actions/checkout@v6 with: fetch-depth: 0 - name: Create Package run: | dotnet build src/Autofac.EasyPropInject.csproj -c Release -p:AssemblyVersion=${{ needs.version.outputs.version }} -p:PackageVersion=${{ needs.version.outputs.version }} dotnet pack src/Autofac.EasyPropInject.csproj -c Release -p:AssemblyVersion=${{ needs.version.outputs.version }} -p:PackageVersion=${{ needs.version.outputs.version }} --output nget_pkg - - name: Create Release and Tag - id: create_release - uses: actions/create-release@latest - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token + - name: Create Release + uses: softprops/action-gh-release@v2 with: - tag_name: v${{ needs.version.outputs.version }} - release_name: Release v${{ needs.version.outputs.version }} + tag_name: v${{ needs.version.outputs.version }} + name: Release v${{ needs.version.outputs.version }} body: | # Release Info Version ${{ needs.version.outputs.version }} ## Info @@ -114,36 +108,12 @@ jobs: ${{fromJSON(needs.prepublish.outputs.changeinfo)}} draft: false prerelease: false + files: | + ./nget_pkg/Autofac.EasyPropInject.${{ needs.version.outputs.version }}.nupkg + src/bin/Release/net10.0/Autofac.EasyPropInject.dll - name: Delete Release Tag - if: ${{needs.version.outputs.tag}} - uses: dev-drprasad/delete-tag-and-release@v1.0 - with: - tag_name: ${{needs.version.outputs.tag}} - github_token: ${{ secrets.GITHUB_TOKEN }} - delete_release: false - - name: Upload Release Asset Pkg - id: upload-release-asset - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps - asset_path: ./nget_pkg/Autofac.EasyPropInject.${{ needs.version.outputs.version }}.nupkg - asset_name: Autofac.EasyPropInject.${{ needs.prepublish.version.version }}.nupkg - asset_content_type: application/zip - - name: Upload Release Asset DLL - id: upload-release-asset2 - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps - asset_path: src/bin/Release/netstandard2.1/Autofac.EasyPropInject.dll - asset_name: Autofac.EasyPropInject.dll - asset_content_type: application/octet-stream + if: ${{ needs.version.outputs.tag }} + run: git push --delete origin ${{ needs.version.outputs.tag }} - name: Publish package to nuget id: nugetpush - run: dotnet nuget push "nget_pkg/Autofac.EasyPropInject.${{ needs.version.outputs.version }}.nupkg" -k ${{secrets.NUGET_KEY}} -s https://api.nuget.org/v3/index.json - - - + run: dotnet nuget push "nget_pkg/Autofac.EasyPropInject.${{ needs.version.outputs.version }}.nupkg" -k ${{secrets.NUGET_KEY}} -s https://api.nuget.org/v3/index.json diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 7d6b2b5..957850e 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -2,20 +2,20 @@ name: Pull Request Check on: pull_request: branches: - - master + - master jobs: test: - runs-on: windows-latest + runs-on: ubuntu-latest steps: - name: Checkout Sources - uses: actions/checkout@v2 + uses: actions/checkout@v6 with: fetch-depth: 0 - - name: Setup .NET 68 - uses: actions/setup-dotnet@v4 + - name: Setup .NET 10 + uses: actions/setup-dotnet@v5 with: - dotnet-version: 8.0.x + dotnet-version: 10.0.x - name: "Build and Test" run: | dotnet build - dotnet test \ No newline at end of file + dotnet test diff --git a/Autofac.EasyPropInject.sln b/Autofac.EasyPropInject.sln index 5131211..04d21ff 100644 --- a/Autofac.EasyPropInject.sln +++ b/Autofac.EasyPropInject.sln @@ -9,7 +9,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Autofac.EasyPropInject", "s EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{6970F006-BA29-4CC6-9D54-F7F22322F61B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autofac.EasyPropInject.Testing", "tests\Autofac.EasyPropInject.Testing\Autofac.EasyPropInject.Testing.csproj", "{3BEF2E53-4346-45B2-935B-2E7DCA48EF99}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Autofac.EasyPropInject.Testing", "tests\Autofac.EasyPropInject.Testing\Autofac.EasyPropInject.Testing.csproj", "{3BEF2E53-4346-45B2-935B-2E7DCA48EF99}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..2c137f4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,73 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [3.0.0] +### Added +- `EasyPropInjectOptions`, configurable via `AddEasyPropInject(options => ...)` +- `UnresolvedPropertyBehavior` to choose what happens to a `[FromAutofac]` property whose service is not + registered: `Skip` (default, leave it untouched) or `SetNull` (the behaviour of 2.x and earlier) +- A `net10.0` build next to the existing `netstandard2.1` one + +### Changed +- Upgraded to Autofac 9.x +- Resolving is roughly three times faster. Measured over 2,000,000 resolves on .NET 10: a component with + decorated properties went from ~3.2s to ~1.0s, a component without any from ~2.0s to ~0.7s. Two things + got it there: + - Property metadata (the decorated properties, the service to resolve for each of them and the setter) is + collected once per type and cached. Previously every single resolve called `GetProperties()` on the + concrete type and asked every property for its attributes + - Properties are written through emitted setters instead of `PropertyInfo.SetValue`, which also removes + the boxing of every assignment +- EasyPropInject is now added as a service middleware source instead of hooking the registry's `Registered` + event and every registration's `PipelineBuilding` event. One middleware instance is shared by the whole + container instead of allocating one per component registration, and `AddEasyPropInject()` may be called at + any point while configuring the builder — before, after or in between registrations. The README used to + claim it had to come first; that restriction is gone and is covered by tests +- Shared instances are explicitly skipped once they have been activated (`NewInstanceActivated`), rather + than relying on the resolve pipeline to short-circuit before the middleware is reached +- A decorated property without a setter now throws an `InvalidOperationException` naming the type and the + property instead of an opaque `ArgumentException` from deep inside reflection +- `FromAutofacAttribute` is `sealed` and its `ResolveFromRegisteredType` is annotated as nullable + +### Fixed +- Private and protected properties declared on a **base** class were never injected. Reflection does not + return non-public members of base types, so the type hierarchy is now walked explicitly +- A property whose service could not be resolved was unconditionally overwritten with `null`, silently + wiping any value assigned in the constructor. The result of the resolve attempt is now respected — see + `UnresolvedPropertyBehavior` if you relied on the old behaviour + +## [2.0.0] +### Changed +- Upgraded to Autofac 8.x + +## [1.2.5] +### Added +- Support for private and protected properties + +### Changed +- Upgraded to Autofac 6.3.x + +## [1.2.4] +### Changed +- Upgraded to Autofac 6.2.x + +## [1.2.3] +### Changed +- Upgraded to Autofac 6.1.x + +## [1.2.0] +### Added +- `FromAutofacAttribute.ResolveFromRegisteredType` to load a property as a different type from the container + +### Changed +- Reimplemented Easy Prop Inject for Autofac 6.x + +## [1.1.1] +### Changed +- Support for Autofac 5.x + +## [1.0.0] +### Added +- Initial release with tests diff --git a/README.md b/README.md index 139f1c8..de975f8 100644 --- a/README.md +++ b/README.md @@ -1,81 +1,168 @@ -[![Nuget](https://img.shields.io/nuget/v/Autofac.EasyPropinject?style=flat)](https://www.nuget.org/packages/Autofac.EasyPropInject/) - [![Paypal Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/donate/?hosted_button_id=SVZHLRTQ6H4VL) +[![Nuget](https://img.shields.io/nuget/v/Autofac.EasyPropInject?style=flat-square)](https://www.nuget.org/packages/Autofac.EasyPropInject/) [![Downloads](https://img.shields.io/nuget/dt/Autofac.EasyPropInject)](https://www.nuget.org/packages/Autofac.EasyPropInject/) [![Paypal Donate](https://img.shields.io/badge/donate-paypal-blue)](https://www.paypal.com/donate/?hosted_button_id=SVZHLRTQ6H4VL) [![Pull Request Check](https://img.shields.io/github/actions/workflow/status/nfMalde/Autofac.EasyPropInject/pr.yml)](https://github.com/nfMalde/Autofac.EasyPropInject/actions/workflows/pr.yml) +# Autofac.EasyPropInject (by Malte) +Attribute based property injection for [Autofac](https://github.com/autofac/Autofac), without any other helper libraries. +Decorate a property with `[FromAutofac]` and it is resolved from the container while the component is activated — public, protected and private properties all work. +Property metadata is collected once per type and written through emitted setters, so after the first resolve the injection costs close to nothing. -# Important! -Due to new Autofac v.8 Version - older versions stay as they are. Updates only occur to latest version released. +## Requirements +Autofac.EasyPropInject requires Autofac 9.x and a project targeting `net10.0` or anything compatible with `netstandard2.1`. -# Autofac.EasyPropInject -An extension i created to make it possible to to inject properties by attribute, without any other helper libs in .NET Standard for [Autofac](https://github.com/autofac/Autofac). +**External Libraries** +This library uses the following library to achieve its functionality: +* [Autofac](https://github.com/autofac/Autofac) -# Install -## Nuget -`Install-Package Autofac.EasyPropInject` +## Install +Using the NuGet package manager: +```bash +Install-Package Autofac.EasyPropInject +``` -## DotNetCli -`dotnet add package Autofac.EasyPropInject` +Using the .NET CLI: +```bash +dotnet add package Autofac.EasyPropInject +``` -# Contribute / Donations -If you got any Ideas to improve my projects feel free to send an pull request. +Enable it in your application: +```csharp +// Startup.cs / Program.cs +using Autofac; +using Autofac.EasyPropInject; -If you like my work and want to support me (or want to buy me a coffee/beer) paypal donation are more than appreciated. +var builder = new ContainerBuilder(); - [![Paypal Donate](https://www.paypalobjects.com/en_US/DK/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/donate/?hosted_button_id=SVZHLRTQ6H4VL) +builder.AddEasyPropInject(); -# Usage -## Startup.cs -Go to "ConfigureServices" -Make sure that you create the Autofac Container as usual for your Framework (Supported is .NET Standard 2+) like its described here: -https://autofac.readthedocs.io/en/latest/integration/index.html +// Add your services as usual +builder.RegisterType().As(); +IContainer container = builder.Build(); +``` -and then you create the instance BEFORE any registration. -```c# - public IServiceProvider ConfigureServices(IServiceCollection services) - { - ...... - var builder = new ContainerBuilder().AddEasyPropInject(); - - //Add your services now as usual - } - +> **Note:** the call can go anywhere while configuring the builder — before, after or in between your +> registrations. Older versions of this README claimed it had to come first; that is no longer the case and +> it is covered by tests. + +Set up the Autofac container the way your framework expects — see the +[Autofac integration documentation](https://autofac.readthedocs.io/en/latest/integration/index.html). + +## Configuration +No configuration is required to use Autofac.EasyPropInject. If you want to change the defaults, pass a +callback to `AddEasyPropInject`: + +```csharp +builder.AddEasyPropInject(options => +{ + // Restore the behaviour of 2.x: overwrite a property with null when it cannot be resolved + options.UnresolvedBehavior = UnresolvedPropertyBehavior.SetNull; +}); ``` -## Usage in the Code -```c# +### Configuration Entries and Their Meanings + +| Option | Description | Default Value | Type | +|---------------------|-----------------------------------------------------------------------------|---------------|-----------------------------| +| UnresolvedBehavior | What happens to a decorated property whose service is not registered in the container. `Skip` leaves the property untouched, so a value assigned in the constructor survives. `SetNull` overwrites it with `null`, which is what EasyPropInject 2.x and earlier did | Skip | UnresolvedPropertyBehavior | + +## Usage + +### The Attribute +To inject a property, decorate it with `FromAutofacAttribute`. +This is the simple way — no constructor plumbing, no service locator. + +#### Arguments: +| Name | Description | +|-------------------------------|-----------------------------------------------------------------------------| +| Type resolveFromRegisteredType | Look this type up in the container instead of the declared property type. If null, empty, or not given, the declared property type is used. | + +#### Examples +```csharp using Autofac.EasyPropInject.Annotations; -public class MyClass:IMyInterface -{ - public MyClass(ISomeOtherInterface someService) - { - + +public class MyClass : IMyInterface +{ + public MyClass(ISomeOtherInterface someService) + { } - - [FromAutofac] - public IUnitOfWork unit { get;set; } + [FromAutofac] + public IUnitOfWork Unit { get; set; } - [FromAutofac] //Since Autofac.EasyPropInject@1.2.5: Support for protected properties - protected IMyService serviceProtected {get;set;} + [FromAutofac] // Since 1.2.5: support for protected properties + protected IMyService ServiceProtected { get; set; } - [FromAutofac] //Since Autofac.EasyPropInject@1.2.5: Support for private properties - private IMyService2 servicePrivate {get;set;} + [FromAutofac] // Since 1.2.5: support for private properties + private IMyService2 ServicePrivate { get; set; } [FromAutofac(typeof(IUnitOfWork))] - public UnitOfWorkBaseClass unit2 {get;set;} + public UnitOfWorkBaseClass Unit2 { get; set; } +} +``` + +Once `IMyInterface` is resolved and activated, EasyPropInject resolves every decorated property from the +current container. Since 3.0.0, private and protected properties declared on a **base** class are picked up +as well. + +The property must have a setter — `init` accessors are fine. A decorated property without one throws an +`InvalidOperationException` naming the type and the property. + +### Resolving as a Different Type +`[FromAutofac(typeof(IUnitOfWork))]` resolves `IUnitOfWork` from the container and assigns it to a property +declared as `UnitOfWorkBaseClass`. + +> **Warning:** this feature is handy but truly unsafe. No compile time check and no type check at resolve +> time can tell you that the registered implementation of `IUnitOfWork` really is a `UnitOfWorkBaseClass` — +> be sure of what you are doing. + +### Unresolvable Properties +By default a property whose service is not registered is left exactly as it is: + +```csharp +public class MyClass : IMyInterface +{ + public MyClass() + { + this.Optional = new NullLogger(); + } + + [FromAutofac] + public ILogger Optional { get; set; } // stays a NullLogger if ILogger is not registered } ``` -Once ``IMyInterface`` is resolved and activated EasyPropInject Middleware will try to resolve the types of unit and unit2. -In this case EasyPropInject will try to resolve IUnitOfWork from current container and will try to set and Instance of IUnitOfWork to unit2 and use it as UnitOfWorkBaseClass. -*Warning* -Since the type casting feature new in 1.2.x of EasyPropInject is handy sometimes its truly unsafe and you should to be sure what you are doing. - - -# Whats new? -* 2.0.0 - Upgraded to latest Autofac (8.x) -* 1.2.5 - Upgraded to Autofac 6.3.x, Added support for private and protected properties See tests for example (https://github.com/nfMalde/Autofac.EasyPropInject/blob/1.2.x/tests/Autofac.EasyPropInject.Testing/InjectionTests.cs) -* 1.2.4 - Upgraded to Autofac 6.2.x -* 1.2.3 - Upgraded to Autofac 6.1.x -* 1.2.0 - Implemented Easy Prop Inject for Autofac 6.x and added the feature to load an property as different type from IContainer. See FromAutofacAttribute. -* 1.1.1 - Easy Prop Inject now supports Autofac 5.x -* 1.0.0 - Added Tests + +Set `UnresolvedBehavior` to `UnresolvedPropertyBehavior.SetNull` to get the 2.x behaviour back, where the +property is overwritten with `null` instead. + +## Performance + +EasyPropInject sits in the resolve pipeline of every component, so it is built to get out of the way. +Version 3.0.0 resolves roughly three times faster than 2.x — measured over 2,000,000 resolves on .NET 10: + +| Scenario | 2.x | 3.0.0 | +|----------------------------------------------|---------|---------| +| Component **with** `[FromAutofac]` properties | ~3.2 s | ~1.0 s | +| Component **without** any attributes | ~2.0 s | ~0.7 s | + +What changed: + +* **Metadata is cached per type.** The decorated properties, the Autofac `Service` to resolve for each of + them and the setter to use are worked out once and reused. Up to 2.x every resolve called + `GetProperties()` on the concrete type and asked every single property for its attributes. +* **Types without decorated properties cost a dictionary lookup.** They cache an empty result and leave the + middleware immediately — which is why components that never use the attribute got faster too. +* **Setters are emitted, not reflected.** Each property gets a `DynamicMethod` that assigns the value + directly, which avoids the overhead and the boxing of `PropertyInfo.SetValue`. Where dynamic code is not + available (AOT), it falls back to reflection automatically. +* **Shared instances are injected once**, when they are activated, and skipped explicitly on every resolve + after that. +* **One middleware instance per container** instead of one per component registration. + +## Changelog +See [CHANGELOG.md](CHANGELOG.md). + +## Contribute / Donations +If you have any ideas to improve my projects, feel free to send a pull request. + +If you like my work and want to support me (or want to buy me a coffee/beer), PayPal donations are more than appreciated. + +[![Paypal Donate](https://img.shields.io/badge/donate-paypal-blue)](https://www.paypal.com/donate/?hosted_button_id=SVZHLRTQ6H4VL) [![Nuget](https://img.shields.io/nuget/v/Autofac.EasyPropInject?style=flat-square)](https://www.nuget.org/packages/Autofac.EasyPropInject/) diff --git a/nugetdocs/README.md b/nugetdocs/README.md deleted file mode 100644 index 45ed94c..0000000 --- a/nugetdocs/README.md +++ /dev/null @@ -1,83 +0,0 @@ -[![Nuget](https://img.shields.io/nuget/v/Autofac.EasyPropinject?style=flat-square)](https://www.nuget.org/packages/Autofac.EasyPropInject/) - [![Paypal Donate](https://img.shields.io/badge/DONATE%E2%99%A5-PAYPAL-blue?style=flat-square&logo=paypal)](https://www.paypal.com/donate/?hosted_button_id=SVZHLRTQ6H4VL) - [![Github](https://img.shields.io/badge/nfMalde-Autofac.EasyPropInject-lightgrey?style=flat-square&logo=github)](https://github.com/nfMalde/Autofac.EasyPropInject) - - -# Important! -Due to new Autofac v.8 Version - older versions stay as they are. Updates only occur to latest version released. - - -# Autofac.EasyPropInject -An extension i created to make it possible to to inject properties by attribute, without any other helper libs in .NET Core for [Autofac](https://github.com/autofac/Autofac). - -# Install -## Nuget -`Install-Package Autofac.EasyPropInject` - -## DotNetCli -`dotnet add package Autofac.EasyPropInject` - -# Contribute / Donations -If you got any Ideas to improve my projects feel free to send an pull request. - -If you like my work and want to support me (or want to buy me a coffee/beer) paypal donation are more than appreciated. - - [![Paypal Donate](https://img.shields.io/badge/DONATE%E2%99%A5-PAYPAL-blue?style=for-the-badge&logo=paypal)](https://www.paypal.com/donate/?hosted_button_id=SVZHLRTQ6H4VL) - -# Usage -## Startup.cs -Go to "ConfigureServices" -Make sure that you create the Autofac Container as usual for your Framework (Supported is .NET Standard 2+) like its described here: -https://autofac.readthedocs.io/en/latest/integration/index.html - - -and then you create the instance BEFORE any registration. -```c# - public IServiceProvider ConfigureServices(IServiceCollection services) - { - ...... - var builder = new ContainerBuilder().AddEasyPropInject(); - - //Add your services now as usual - } - -``` - -## Usage in the Code -```c# -using Autofac.EasyPropInject.Annotations; -public class MyClass:IMyInterface -{ - public MyClass(ISomeOtherInterface someService) - { - - } - - [FromAutofac] - public IUnitOfWork unit { get;set; } - - - [FromAutofac] //Since Autofac.EasyPropInject@1.2.5: Support for protected properties - protected IMyService serviceProtected {get;set;} - - [FromAutofac] //Since Autofac.EasyPropInject@1.2.5: Support for private properties - private IMyService2 servicePrivate {get;set;} - - [FromAutofac(typeof(IUnitOfWork))] - public UnitOfWorkBaseClass unit2 {get;set;} -} -``` -Once ``IMyInterface`` is resolved and activated EasyPropInject Middleware will try to resolve the types of unit and unit2. -In this case EasyPropInject will try to resolve IUnitOfWork from current container and will try to set and Instance of IUnitOfWork to unit2 and use it as UnitOfWorkBaseClass. -*Warning* -Since the type casting feature new in 1.2.x of EasyPropInject is handy sometimes its truly unsafe and you should to be sure what you are doing. - - -# Whats new? -* 2.0.0 - Upgraded to latest Autofac (8.x) -* 1.2.5 - Upgraded to Autofac 6.3.x, Added support for private and protected properties See tests for example (https://github.com/nfMalde/Autofac.EasyPropInject/blob/1.2.x/tests/Autofac.EasyPropInject.Testing/InjectionTests.cs) -* 1.2.4 - Upgraded to Autofac 6.2.x -* 1.2.3 - Upgraded to Autofac 6.1.x -* 1.2.0 - Implemented Easy Prop Inject for Autofac 6.x and added the feature to load an property as different type from IContainer. See FromAutofacAttribute. -* 1.1.1 - Easy Prop Inject now supports Autofac 5.x -* 1.0.0 - Added Tests diff --git a/src/Annotations/FromAutofacAttribute.cs b/src/Annotations/FromAutofacAttribute.cs index 9f130bb..b5371fc 100644 --- a/src/Annotations/FromAutofacAttribute.cs +++ b/src/Annotations/FromAutofacAttribute.cs @@ -1,30 +1,30 @@ -using System; +using System; namespace Autofac.EasyPropInject.Annotations { /// /// FromAutofac Attribute to mark properties for injection /// - [System.AttributeUsage(System.AttributeTargets.Property, + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] - public class FromAutofacAttribute : Attribute + public sealed class FromAutofacAttribute : Attribute { /// - /// If set, EasyPropInject will try to load the type out of the autofac container instead of the type that property is decalared + /// If set, EasyPropInject will try to load the type out of the autofac container instead of the type that property is declared as. /// /// /// The type of the resolve from registered. /// - public Type ResolveFromRegisteredType { get; set; } = null; + public Type? ResolveFromRegisteredType { get; set; } /// /// Initializes a new instance of the class. /// /// Look up for this type instead of the declared type. - public FromAutofacAttribute(Type resolveFromRegisteredType = null) + public FromAutofacAttribute(Type? resolveFromRegisteredType = null) { this.ResolveFromRegisteredType = resolveFromRegisteredType; } } -} \ No newline at end of file +} diff --git a/src/Autofac.EasyPropInject.csproj b/src/Autofac.EasyPropInject.csproj index 211cdeb..d7c1dad 100644 --- a/src/Autofac.EasyPropInject.csproj +++ b/src/Autofac.EasyPropInject.csproj @@ -1,9 +1,20 @@ - + - netstandard2.1 + netstandard2.1;net10.0 + 3.0.0 + latest + enable + true true - Allows to inject properties of classes by using annotations. + + Malte Peters autofac, injections, annotations, dependency injection, property injection Unlicense @@ -11,14 +22,24 @@ https://github.com/nfMalde/Autofac.EasyPropInject https://github.com/nfMalde/Autofac.EasyPropInject GIT - Upgraded to Autofac 8.x - README.md - + README.md + + ...) + * AddEasyPropInject() can be called at any point while configuring the container - before, after or in between registrations + ]]> - - + + + + + diff --git a/src/EasyPropInject.cs b/src/EasyPropInject.cs index 3ff94dc..b6b287f 100644 --- a/src/EasyPropInject.cs +++ b/src/EasyPropInject.cs @@ -1,4 +1,5 @@ -using Autofac.EasyPropInject.Middleware; +using Autofac.EasyPropInject.Internal; +using System; namespace Autofac.EasyPropInject { @@ -8,27 +9,44 @@ namespace Autofac.EasyPropInject public static class EasyPropInject { /// - /// Adds the event listeners for auto injecting properties + /// Enables automatic injection of properties decorated with + /// . /// /// ContainerBuilder /// ContainerBuilder + /// + /// This may be called at any point while configuring the builder - before, after or in between + /// registrations. + /// + /// Thrown if is null. public static ContainerBuilder AddEasyPropInject(this ContainerBuilder builder) + => builder.AddEasyPropInject(null); + + /// + /// Enables automatic injection of properties decorated with + /// . + /// + /// ContainerBuilder + /// Callback used to configure the injection behaviour. + /// ContainerBuilder + /// + /// This may be called at any point while configuring the builder - before, after or in between + /// registrations. + /// + /// Thrown if is null. + public static ContainerBuilder AddEasyPropInject(this ContainerBuilder builder, Action? configure) { - builder.RegisterCallback(c => + if (builder == null) { - c.Registered += (sender, args) => - { - // The PipelineBuilding event fires just before the pipeline is built, and - // middleware can be added inside it. - args.ComponentRegistration.PipelineBuilding += (s, pipeline) => - { - // Add EasyPropInjectMiddleware - pipeline.Use(new EasyPropInjectMiddleware()); - }; - }; - }); + throw new ArgumentNullException(nameof(builder)); + } + + EasyPropInjectOptions options = new EasyPropInjectOptions(); + configure?.Invoke(options); + + builder.RegisterServiceMiddlewareSource(new EasyPropInjectMiddlewareSource(options)); return builder; } } -} \ No newline at end of file +} diff --git a/src/EasyPropInjectOptions.cs b/src/EasyPropInjectOptions.cs new file mode 100644 index 0000000..c35a82b --- /dev/null +++ b/src/EasyPropInjectOptions.cs @@ -0,0 +1,33 @@ +namespace Autofac.EasyPropInject +{ + /// + /// Controls what happens to a property decorated with + /// when its service cannot be resolved + /// from the container. + /// + public enum UnresolvedPropertyBehavior + { + /// + /// Leave the property untouched. Whatever the constructor (or an object initializer) assigned + /// stays in place. This is the default. + /// + Skip = 0, + + /// + /// Assign null to the property. This is the behaviour of EasyPropInject 2.x and earlier. + /// + SetNull = 1, + } + + /// + /// Options for the EasyPropInject property injection. + /// + public sealed class EasyPropInjectOptions + { + /// + /// Gets or sets the behaviour used when a decorated property cannot be resolved from the container. + /// Defaults to . + /// + public UnresolvedPropertyBehavior UnresolvedBehavior { get; set; } = UnresolvedPropertyBehavior.Skip; + } +} diff --git a/src/Internal/EasyPropInjectMiddlewareSource.cs b/src/Internal/EasyPropInjectMiddlewareSource.cs new file mode 100644 index 0000000..faaeca4 --- /dev/null +++ b/src/Internal/EasyPropInjectMiddlewareSource.cs @@ -0,0 +1,47 @@ +using Autofac.Core; +using Autofac.Core.Registration; +using Autofac.Core.Resolving.Pipeline; +using Autofac.EasyPropInject.Middleware; +using System; + +namespace Autofac.EasyPropInject.Internal +{ + /// + /// Adds the to the pipeline of every service. + /// + /// + /// A middleware source is consulted while a service pipeline is being built, which happens after the + /// container has been fully configured. That keeps + /// + /// independent of registration order and needs a single middleware instance for the whole container, + /// where the previous approach - subscribing to "Registered" and then to every registration's + /// "PipelineBuilding" event - allocated one per component registration. + /// + internal sealed class EasyPropInjectMiddlewareSource : IServiceMiddlewareSource + { + /// + /// The single middleware instance shared by every service pipeline. + /// + private readonly EasyPropInjectMiddleware middleware; + + /// + /// Initializes a new instance of the class. + /// + /// The options controlling the injection. + internal EasyPropInjectMiddlewareSource(EasyPropInjectOptions options) + { + this.middleware = new EasyPropInjectMiddleware(options); + } + + /// + /// Adds the EasyPropInject middleware to the pipeline of the given service. + /// + /// The service whose pipeline is being built. + /// The services available in the registry. + /// The pipeline builder for the service. + public void ProvideMiddleware(Service service, IComponentRegistryServices availableServices, IResolvePipelineBuilder pipelineBuilder) + { + pipelineBuilder.Use(this.middleware); + } + } +} diff --git a/src/Internal/InjectableProperty.cs b/src/Internal/InjectableProperty.cs new file mode 100644 index 0000000..cf544ea --- /dev/null +++ b/src/Internal/InjectableProperty.cs @@ -0,0 +1,55 @@ +using Autofac.Core; +using System; + +namespace Autofac.EasyPropInject.Internal +{ + /// + /// A pre-computed description of a single property decorated with + /// . + /// + /// + /// Everything that can be worked out from metadata alone - the service to resolve and the + /// delegate used to assign the value - is computed once per type by + /// and reused for every resolve afterwards. + /// + internal sealed class InjectableProperty + { + /// + /// Initializes a new instance of the class. + /// + /// The type declaring the property. + /// The property name. + /// The service to resolve for this property. + /// The setter used to assign the resolved instance. + internal InjectableProperty(Type declaringType, string propertyName, Service service, Action setter) + { + this.DeclaringType = declaringType; + this.PropertyName = propertyName; + this.Service = service; + this.Setter = setter; + } + + /// + /// Gets the type declaring the property. Used for diagnostics only. + /// + internal Type DeclaringType { get; } + + /// + /// Gets the name of the property. Used for diagnostics only. + /// + internal string PropertyName { get; } + + /// + /// Gets the service that has to be resolved for this property. This is a + /// for the type given to + /// or, if that is not + /// set, for the declared property type. + /// + internal Service Service { get; } + + /// + /// Gets the delegate assigning a resolved instance to the property of a given target object. + /// + internal Action Setter { get; } + } +} diff --git a/src/Internal/InjectablePropertyCache.cs b/src/Internal/InjectablePropertyCache.cs new file mode 100644 index 0000000..52bdfb9 --- /dev/null +++ b/src/Internal/InjectablePropertyCache.cs @@ -0,0 +1,163 @@ +using Autofac.Core; +using Autofac.EasyPropInject.Annotations; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Reflection; +using System.Reflection.Emit; + +namespace Autofac.EasyPropInject.Internal +{ + /// + /// Caches, per concrete type, the properties decorated with + /// together with everything needed to inject them. + /// + /// + /// Reflection is expensive and the result never changes for a given type, so it is done exactly once + /// per type. Every later resolve of that type only costs a dictionary lookup. Types without any + /// decorated property cache an empty array, which makes them practically free. + /// + internal static class InjectablePropertyCache + { + /// + /// The binding flags used to look at a single level of the type hierarchy. + /// is required because reflection does not return private + /// properties of base classes otherwise. + /// + private const BindingFlags DeclaredInstanceProperties = + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; + + /// + /// The shared result for every type that has nothing to inject. + /// + private static readonly InjectableProperty[] Empty = new InjectableProperty[0]; + + /// + /// The per type cache. + /// + private static readonly ConcurrentDictionary Cache = + new ConcurrentDictionary(); + + /// + /// Gets the injectable properties of the given type, building them on first use. + /// + /// The concrete type of the resolved instance. + /// The decorated properties, or an empty array if there are none. + internal static InjectableProperty[] Get(Type type) => Cache.GetOrAdd(type, BuildDescriptors); + + /// + /// Walks the type and all of its base types and builds a descriptor for every decorated property. + /// + /// The type to inspect. + /// The descriptors for the decorated properties. + private static InjectableProperty[] BuildDescriptors(Type type) + { + List? descriptors = null; + + // Properties shadowed by a derived type ("new") must only be injected once - the most derived + // declaration wins, which is why the hierarchy is walked from the concrete type upwards. + HashSet? seen = null; + + for (Type? current = type; current != null && current != typeof(object); current = current.BaseType) + { + foreach (PropertyInfo property in current.GetProperties(DeclaredInstanceProperties)) + { + // Indexers cannot be injected. + if (property.GetIndexParameters().Length > 0) + { + continue; + } + + FromAutofacAttribute? attribute = property.GetCustomAttribute(inherit: true); + + if (attribute == null) + { + continue; + } + + seen ??= new HashSet(StringComparer.Ordinal); + + if (!seen.Add(property.Name)) + { + continue; + } + + MethodInfo? setMethod = property.SetMethod; + + if (setMethod == null) + { + throw new InvalidOperationException( + $"Property '{current.FullName}.{property.Name}' is decorated with [FromAutofac] but has no setter. " + + "EasyPropInject can only inject properties that can be written to."); + } + + Type serviceType = attribute.ResolveFromRegisteredType ?? property.PropertyType; + + descriptors ??= new List(); + descriptors.Add(new InjectableProperty( + current, + property.Name, + new TypedService(serviceType), + BuildSetter(property, setMethod))); + } + } + + return descriptors == null ? Empty : descriptors.ToArray(); + } + + /// + /// Builds a delegate assigning a value to the given property. + /// + /// The property to build a setter for. + /// The set accessor of . + /// A delegate taking the target instance and the value to assign. + /// + /// The delegate is emitted as a with skipVisibility enabled, which + /// is considerably faster than and - unlike a + /// compiled LINQ expression - is also able to write private and protected properties. + /// Where dynamic code is not available (AOT) or emitting fails, reflection is used instead. + /// + private static Action BuildSetter(PropertyInfo property, MethodInfo setMethod) + { + Type? declaringType = property.DeclaringType; + + // A value typed declaring type would be mutated on a boxed copy, and a value typed property + // cannot take a null reference. Both are rare enough that reflection is a good enough answer. + if (declaringType == null || declaringType.IsValueType || property.PropertyType.IsValueType) + { + return (instance, value) => property.SetValue(instance, value); + } + +#if NET10_0_OR_GREATER + if (!System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported) + { + return (instance, value) => property.SetValue(instance, value); + } +#endif + + try + { + DynamicMethod method = new DynamicMethod( + "EasyPropInject_set_" + declaringType.Name + "_" + property.Name, + null, + new[] { typeof(object), typeof(object) }, + declaringType.Module, + skipVisibility: true); + + ILGenerator il = method.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Castclass, declaringType); + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Castclass, property.PropertyType); + il.Emit(setMethod.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (Action)method.CreateDelegate(typeof(Action)); + } + catch (Exception) + { + return (instance, value) => property.SetValue(instance, value); + } + } + } +} diff --git a/src/Middleware/EasyPropInjectMiddleware.cs b/src/Middleware/EasyPropInjectMiddleware.cs index 18490b9..0d96dae 100644 --- a/src/Middleware/EasyPropInjectMiddleware.cs +++ b/src/Middleware/EasyPropInjectMiddleware.cs @@ -1,75 +1,100 @@ -using Autofac.Core.Resolving.Pipeline; +using Autofac.Core.Resolving.Pipeline; using Autofac.EasyPropInject.Annotations; +using Autofac.EasyPropInject.Internal; using System; -using System.Reflection; namespace Autofac.EasyPropInject.Middleware { /// - /// Autofac Resolve Pipeline Middleware for detecting properties decorated with "FromAutofacAttribute" + /// Autofac resolve pipeline middleware injecting properties decorated with + /// . /// /// - public class EasyPropInjectMiddleware : IResolveMiddleware + public sealed class EasyPropInjectMiddleware : IResolveMiddleware { /// - /// Gets the phase of the resolve pipeline at which to execute. + /// The options controlling the injection. /// - public PipelinePhase Phase => PipelinePhase.RegistrationPipelineStart; + private readonly EasyPropInjectOptions options; /// - /// Invoked when this middleware is executed as part of an active . The middleware should usually call - /// the method in order to continue the pipeline, unless the middleware fully satisfies the request. + /// Initializes a new instance of the class using the + /// default options. /// - /// The context for the resolve request. - /// The method to invoke to continue the pipeline execution; pass this method the argument. - public void Execute(ResolveRequestContext context, Action next) + public EasyPropInjectMiddleware() + : this(new EasyPropInjectOptions()) { - // Call the next middleware in the pipeline. - next(context); + } - // Inject decorated properties - this._injectEasily(context); + /// + /// Initializes a new instance of the class. + /// + /// The options controlling the injection. + /// Thrown if is null. + public EasyPropInjectMiddleware(EasyPropInjectOptions options) + { + this.options = options ?? throw new ArgumentNullException(nameof(options)); } /// - /// Collects all properties of current resolved instance that have the "FromAutofac" Attribute. + /// Gets the phase of the resolve pipeline at which to execute. + /// + public PipelinePhase Phase => PipelinePhase.ServicePipelineEnd; + + /// + /// Invoked when this middleware is executed as part of an active . + /// Properties are injected on the way out of the pipeline, once the instance has been activated. /// - /// The context. - private void _injectEasily(ResolveRequestContext context) + /// The context for the resolve request. + /// The method to invoke to continue the pipeline execution. + public void Execute(ResolveRequestContext context, Action next) { - object instance = context.Instance; + // Let the instance be created first. + next(context); - if (instance != null) + // A shared instance that was created by an earlier request already had its properties injected. + // Re-injecting it on every resolve would be pure overhead. + if (!context.NewInstanceActivated) { - var props = instance.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); + return; + } - foreach (PropertyInfo property in props) - { - this._resolve(property, context); - } + object? instance = context.Instance; + + if (instance == null) + { + return; } - } - /// - /// Resolves the specified property. - /// - /// The property. - /// The context. - private void _resolve(PropertyInfo property, ResolveRequestContext context) - { - object instance = context.Instance; + InjectableProperty[] properties = InjectablePropertyCache.Get(instance.GetType()); + + // The overwhelming majority of components have nothing to inject - leave immediately. + if (properties.Length == 0) + { + return; + } - FromAutofacAttribute attr = property.GetCustomAttribute(); + bool setNullWhenUnresolved = this.options.UnresolvedBehavior == UnresolvedPropertyBehavior.SetNull; - if (attr != null) + for (int i = 0; i < properties.Length; i++) { - object propertyInstance = null; - //Get the correct resolving type - Type targetType = attr.ResolveFromRegisteredType != null ? attr.ResolveFromRegisteredType : property.PropertyType; - context.TryResolve(targetType, out propertyInstance); - // Set value to property with the newly resolved instance - property.SetValue(instance, propertyInstance); + InjectableProperty property = properties[i]; + + if (context.TryResolveService(property.Service, out object? value)) + { + property.Setter(instance, value); + } + else if (setNullWhenUnresolved) + { + property.Setter(instance, null); + } } } + + /// + /// Returns a description of this middleware, shown in Autofac resolve tracing. + /// + /// The middleware description. + public override string ToString() => nameof(EasyPropInjectMiddleware); } -} \ No newline at end of file +} diff --git a/tests/Autofac.EasyPropInject.Testing/Autofac.EasyPropInject.Testing.csproj b/tests/Autofac.EasyPropInject.Testing/Autofac.EasyPropInject.Testing.csproj index d22c71d..32cd7b9 100644 --- a/tests/Autofac.EasyPropInject.Testing/Autofac.EasyPropInject.Testing.csproj +++ b/tests/Autofac.EasyPropInject.Testing/Autofac.EasyPropInject.Testing.csproj @@ -1,7 +1,9 @@ - net8.0 + net10.0 + + latest false @@ -11,11 +13,11 @@ - - - - - + + + + + diff --git a/tests/Autofac.EasyPropInject.Testing/InjectionTests.cs b/tests/Autofac.EasyPropInject.Testing/InjectionTests.cs index ffb8d39..eae6b2a 100644 --- a/tests/Autofac.EasyPropInject.Testing/InjectionTests.cs +++ b/tests/Autofac.EasyPropInject.Testing/InjectionTests.cs @@ -1,6 +1,6 @@ using Autofac.EasyPropInject.Testing.mocks; using NUnit.Framework; -using Autofac.EasyPropInject; + namespace Autofac.EasyPropInject.Testing { /// @@ -26,6 +26,8 @@ public void Setup() builder.Register(x => new Mock4()).As(); builder.RegisterType().As(); builder.RegisterType().As(); + builder.RegisterType().As(); + builder.RegisterType().As(); this.container = builder.Build(); } @@ -38,9 +40,9 @@ public void ItShouldInjectPropertiesOfInstanceAndChildInstances() { var m1 = this.container.Resolve(); - Assert.That(m1.Mock2Property != null); - Assert.That(m1.Mock2Property.Mock3Property != null); - Assert.That(m1.Mock2Property.Mock3Property.Mock4ResolvedAsMainType != null); + Assert.That(m1.Mock2Property, Is.Not.Null); + Assert.That(m1.Mock2Property.Mock3Property, Is.Not.Null); + Assert.That(m1.Mock2Property.Mock3Property.Mock4ResolvedAsMainType, Is.Not.Null); } [Test] @@ -48,7 +50,7 @@ public void ItShouldResolvePrivateProperties() { var mPrivate = this.container.Resolve(); - Assert.That(mPrivate.Mock1Test() != null); + Assert.That(mPrivate.Mock1Test(), Is.Not.Null); } [Test] @@ -56,8 +58,45 @@ public void ItShouldResolveProtectedProperties() { var mPrivate = this.container.Resolve(); - Assert.That(mPrivate.GetMockPrivate() != null); - Assert.That(mPrivate.GetMockPrivate().Mock1Test() != null); + Assert.That(mPrivate.GetMockPrivate(), Is.Not.Null); + Assert.That(mPrivate.GetMockPrivate().Mock1Test(), Is.Not.Null); + } + + /// + /// Mock3 declares its property as the concrete Mock4 type but asks for IMock4 to be resolved. + /// + [Test] + public void ItShouldResolveThePropertyAsTheTypeGivenToTheAttribute() + { + var m3 = this.container.Resolve(); + + Assert.That(m3.Mock4ResolvedAsMainType, Is.Not.Null); + Assert.That(m3.Mock4ResolvedAsMainType.Ok(), Is.True); + } + + /// + /// A private property declared on a base class is invisible to a plain GetProperties() call on the + /// concrete type, so the hierarchy has to be walked explicitly. + /// + [Test] + public void ItShouldResolvePrivatePropertiesDeclaredOnABaseClass() + { + var derived = this.container.Resolve(); + + Assert.That(derived.GetMock1FromBase(), Is.Not.Null); + Assert.That(derived.Mock2Property, Is.Not.Null); + } + + /// + /// A component without any decorated property must come out of the container untouched. + /// + [Test] + public void ItShouldLeaveComponentsWithoutDecoratedPropertiesAlone() + { + var plain = this.container.Resolve(); + + Assert.That(plain.Name, Is.EqualTo("plain")); + Assert.That(plain.Untouched, Is.Null); } } -} \ No newline at end of file +} diff --git a/tests/Autofac.EasyPropInject.Testing/OptionsTests.cs b/tests/Autofac.EasyPropInject.Testing/OptionsTests.cs new file mode 100644 index 0000000..abbdd36 --- /dev/null +++ b/tests/Autofac.EasyPropInject.Testing/OptionsTests.cs @@ -0,0 +1,70 @@ +using Autofac.EasyPropInject.Testing.mocks; +using NUnit.Framework; + +namespace Autofac.EasyPropInject.Testing +{ + /// + /// Tests for . + /// + public class OptionsTests + { + /// + /// Builds a container containing but not the service it asks for. + /// + /// The behaviour to configure, or null to keep the default. + /// The built container. + private static IContainer BuildContainer(UnresolvedPropertyBehavior? behavior) + { + ContainerBuilder builder = new ContainerBuilder(); + + if (behavior.HasValue) + { + builder.AddEasyPropInject(options => options.UnresolvedBehavior = behavior.Value); + } + else + { + builder.AddEasyPropInject(); + } + + builder.RegisterType().As(); + + return builder.Build(); + } + + /// + /// The default keeps whatever the constructor assigned. + /// + [Test] + public void ItShouldLeaveAnUnresolvablePropertyUntouchedByDefault() + { + using IContainer container = BuildContainer(null); + + var mock = container.Resolve(); + + Assert.That(mock.Optional, Is.Not.Null); + Assert.That(mock.Optional.Origin, Is.EqualTo("constructor")); + } + + /// + /// Skip is the explicit spelling of the default. + /// + [Test] + public void ItShouldLeaveAnUnresolvablePropertyUntouchedWhenConfiguredToSkip() + { + using IContainer container = BuildContainer(UnresolvedPropertyBehavior.Skip); + + Assert.That(container.Resolve().Optional, Is.Not.Null); + } + + /// + /// SetNull restores the behaviour of EasyPropInject 2.x and earlier. + /// + [Test] + public void ItShouldOverwriteAnUnresolvablePropertyWithNullWhenConfiguredToSetNull() + { + using IContainer container = BuildContainer(UnresolvedPropertyBehavior.SetNull); + + Assert.That(container.Resolve().Optional, Is.Null); + } + } +} diff --git a/tests/Autofac.EasyPropInject.Testing/RegistrationTests.cs b/tests/Autofac.EasyPropInject.Testing/RegistrationTests.cs new file mode 100644 index 0000000..54eafd0 --- /dev/null +++ b/tests/Autofac.EasyPropInject.Testing/RegistrationTests.cs @@ -0,0 +1,123 @@ +using Autofac.EasyPropInject.Testing.mocks; +using NUnit.Framework; +using System; + +namespace Autofac.EasyPropInject.Testing +{ + /// + /// Tests around how and when EasyPropInject is added to the container. + /// + public class RegistrationTests + { + /// + /// The README used to claim AddEasyPropInject() had to be called before any registration. It does + /// not, and this pins that down so the middleware source cannot silently regress into being order + /// dependent. + /// + [Test] + public void ItShouldInjectComponentsRegisteredBeforeAddEasyPropInjectWasCalled() + { + ContainerBuilder builder = new ContainerBuilder(); + + builder.Register(x => new Mock1()).As(); + builder.Register(x => new Mock2()).As(); + builder.Register(x => new Mock3()).As(); + builder.Register(x => new Mock4()).As(); + + // Added last, on purpose. + builder.AddEasyPropInject(); + + using IContainer container = builder.Build(); + + var m1 = container.Resolve(); + + Assert.That(m1.Mock2Property, Is.Not.Null); + Assert.That(m1.Mock2Property.Mock3Property, Is.Not.Null); + } + + /// + /// The other end of the same rule: adding it first still has to work. + /// + [Test] + public void ItShouldTolerateBeingAddedBeforeRegistrations() + { + ContainerBuilder builder = new ContainerBuilder(); + + builder.AddEasyPropInject(); + builder.Register(x => new Mock1()).As(); + builder.Register(x => new Mock2()).As(); + builder.Register(x => new Mock3()).As(); + builder.Register(x => new Mock4()).As(); + + using IContainer container = builder.Build(); + + Assert.That(container.Resolve().Mock2Property, Is.Not.Null); + } + + /// + /// A shared instance is created once, so it must be injected once - not on every resolve. If the + /// middleware ever moved to a phase that runs before sharing short-circuits, this would catch it. + /// + [Test] + public void ItShouldInjectASingleInstanceComponentExactlyOnce() + { + int dependencyActivations = 0; + + ContainerBuilder builder = new ContainerBuilder().AddEasyPropInject(); + + builder.Register(x => + { + dependencyActivations++; + return new Mock4(); + }).As().InstancePerDependency(); + + builder.RegisterType().As().SingleInstance(); + + using IContainer container = builder.Build(); + + for (int i = 0; i < 10; i++) + { + Assert.That(container.Resolve().Dependency, Is.Not.Null); + } + + Assert.That(dependencyActivations, Is.EqualTo(1)); + } + + /// + /// A decorated property without a setter is a programming error and has to say so clearly. + /// + [Test] + public void ItShouldThrowADescriptiveErrorForADecoratedPropertyWithoutASetter() + { + ContainerBuilder builder = new ContainerBuilder().AddEasyPropInject(); + builder.Register(x => new Mock4()).As(); + builder.RegisterType().As(); + + using IContainer container = builder.Build(); + + // Autofac wraps anything thrown inside the pipeline in a DependencyResolutionException. + Exception exception = Assert.Catch(() => container.Resolve()); + string message = Flatten(exception); + + Assert.That(message, Does.Contain(nameof(MockGetOnly.ReadOnlyDependency))); + Assert.That(message, Does.Contain("no setter")); + } + + /// + /// Concatenates the messages of an exception and all of its inner exceptions. + /// + /// The exception to flatten. + /// All messages of the exception chain. + private static string Flatten(Exception exception) + { + string message = string.Empty; + + for (Exception current = exception; current != null; current = current.InnerException) + { + message += current.Message + Environment.NewLine; + } + + return message; + } + } +} diff --git a/tests/Autofac.EasyPropInject.Testing/mocks/MockGetOnly.cs b/tests/Autofac.EasyPropInject.Testing/mocks/MockGetOnly.cs new file mode 100644 index 0000000..28e67ae --- /dev/null +++ b/tests/Autofac.EasyPropInject.Testing/mocks/MockGetOnly.cs @@ -0,0 +1,19 @@ +using Autofac.EasyPropInject.Annotations; + +namespace Autofac.EasyPropInject.Testing.mocks +{ + public interface IMockGetOnly + { + IMock4 ReadOnlyDependency { get; } + } + + /// + /// Decorates a property that cannot be written to. EasyPropInject has to say so instead of failing + /// somewhere inside reflection. + /// + public class MockGetOnly : IMockGetOnly + { + [FromAutofac] + public IMock4 ReadOnlyDependency => null; + } +} diff --git a/tests/Autofac.EasyPropInject.Testing/mocks/MockPlain.cs b/tests/Autofac.EasyPropInject.Testing/mocks/MockPlain.cs new file mode 100644 index 0000000..51ce64d --- /dev/null +++ b/tests/Autofac.EasyPropInject.Testing/mocks/MockPlain.cs @@ -0,0 +1,20 @@ +namespace Autofac.EasyPropInject.Testing.mocks +{ + public interface IMockPlain + { + string Name { get; } + + IMock1 Untouched { get; set; } + } + + /// + /// A component without any decorated property. It must resolve exactly as it would without + /// EasyPropInject - in particular, its properties must not be written to. + /// + public class MockPlain : IMockPlain + { + public string Name => "plain"; + + public IMock1 Untouched { get; set; } + } +} diff --git a/tests/Autofac.EasyPropInject.Testing/mocks/MockPrivateBase.cs b/tests/Autofac.EasyPropInject.Testing/mocks/MockPrivateBase.cs new file mode 100644 index 0000000..ee7300c --- /dev/null +++ b/tests/Autofac.EasyPropInject.Testing/mocks/MockPrivateBase.cs @@ -0,0 +1,32 @@ +using Autofac.EasyPropInject.Annotations; + +namespace Autofac.EasyPropInject.Testing.mocks +{ + /// + /// Base class declaring a private decorated property. Reflection does not return private members of + /// base classes unless the hierarchy is walked explicitly, so this covers that case. + /// + public abstract class MockPrivateBase + { + [FromAutofac] + private IMock1 mock1 { get; set; } + + public IMock1 GetMock1FromBase() => this.mock1; + } + + public interface IMockDerived + { + IMock1 GetMock1FromBase(); + + IMock2 Mock2Property { get; set; } + } + + /// + /// Derived class that declares no decorated property of its own. + /// + public class MockDerived : MockPrivateBase, IMockDerived + { + [FromAutofac] + public IMock2 Mock2Property { get; set; } + } +} diff --git a/tests/Autofac.EasyPropInject.Testing/mocks/MockSingleton.cs b/tests/Autofac.EasyPropInject.Testing/mocks/MockSingleton.cs new file mode 100644 index 0000000..c5c6f67 --- /dev/null +++ b/tests/Autofac.EasyPropInject.Testing/mocks/MockSingleton.cs @@ -0,0 +1,19 @@ +using Autofac.EasyPropInject.Annotations; + +namespace Autofac.EasyPropInject.Testing.mocks +{ + public interface IMockSingleton + { + IMock4 Dependency { get; } + } + + /// + /// Registered as a single instance so the tests can verify that its properties are injected exactly + /// once and not on every resolve. + /// + public class MockSingleton : IMockSingleton + { + [FromAutofac] + public IMock4 Dependency { get; set; } + } +} diff --git a/tests/Autofac.EasyPropInject.Testing/mocks/MockUnresolvable.cs b/tests/Autofac.EasyPropInject.Testing/mocks/MockUnresolvable.cs new file mode 100644 index 0000000..3bd604e --- /dev/null +++ b/tests/Autofac.EasyPropInject.Testing/mocks/MockUnresolvable.cs @@ -0,0 +1,39 @@ +using Autofac.EasyPropInject.Annotations; + +namespace Autofac.EasyPropInject.Testing.mocks +{ + /// + /// A service that is deliberately never registered in the container. + /// + public interface INotRegistered + { + string Origin { get; } + } + + /// + /// The fallback the constructor assigns before EasyPropInject gets a chance to inject. + /// + public class NotRegisteredFallback : INotRegistered + { + public string Origin => "constructor"; + } + + public interface IMockUnresolvable + { + INotRegistered Optional { get; } + } + + /// + /// Decorates a property whose service cannot be resolved and pre-fills it in the constructor. + /// + public class MockUnresolvable : IMockUnresolvable + { + public MockUnresolvable() + { + this.Optional = new NotRegisteredFallback(); + } + + [FromAutofac] + public INotRegistered Optional { get; set; } + } +}