Skip to content

Conversation

@mokarchi
Copy link
Contributor

@mokarchi mokarchi commented Oct 3, 2025

Overview

This PR adds support for keyed service registration in the Scan method, enabling compatibility with .NET 8's keyed dependency injection feature. This allows users to specify service keys during scanning, aligning with the AddKeyedSingleton/AddKeyedScoped/AddKeyedTransient pattern introduced in .NET 8.

Problem

Previously, there was no way to register services with keys when using Scrutor's scanning capabilities. Users who wanted to leverage .NET 8's keyed DI feature had to manually register services, losing the benefits of convention-based scanning.

Solution

Added two new methods to ILifetimeSelector:

  • WithServiceKey(object serviceKey) - Registers all scanned services with a fixed service key
  • WithServiceKey(Func<Type, object?> selector) - Registers services with dynamic keys based on a selector function

Usage Examples

Fixed Service Key

Register all scanned services with the same key:

services.Scan(scan => scan
    .FromAssemblyOf<MyService>()
    .AddClasses()
    .AsImplementedInterfaces()
    .WithServiceKey("my-key")
    .WithTransientLifetime());

// Resolve using the key
var service = provider.GetRequiredKeyedService<IMyService>("my-key");

Dynamic Service Key

Use a selector function to assign different keys based on the implementation type:

services.Scan(scan => scan
    .FromAssemblyOf<IRepository>()
    .AddClasses(c => c.AssignableTo<IRepository>())
    .AsImplementedInterfaces()
    .WithServiceKey(type => type.Name.Replace("Repository", ""))
    .WithScopedLifetime());

// Resolve specific repositories by key
var customerRepo = provider.GetRequiredKeyedService<IRepository>("Customer");
var orderRepo = provider.GetRequiredKeyedService<IRepository>("Order");

Introduced service key registration in the `ILifetimeSelector` interface with two new methods: `WithServiceKey(object serviceKey)` and `WithServiceKey(Func<Type, object?> selector)`. These enable registering services with fixed or dynamically determined service keys.

Updated the `LifetimeSelector` class to handle service key functionality, including adding the `ServiceKeySelectorFn` property, modifying the `Populate` method to support keyed `ServiceDescriptor` creation, and adding helper methods for service key resolution.

Enhanced the `ServiceTypeSelector` class to propagate service key selectors to `LifetimeSelector` instances.

Added unit tests in `ScanningTests.cs` to validate service key registration and resolution, including tests for fixed keys, selector-based keys, and keyed service resolution.

Made minor formatting adjustments and ensured proper validation of the new functionality.
@mokarchi
Copy link
Contributor Author

mokarchi commented Oct 6, 2025

@khellang Could you review this, please?

@khellang khellang merged commit 2cdfc8d into khellang:master Nov 24, 2025
This was referenced Nov 24, 2025
github-merge-queue bot pushed a commit to DFE-Digital/teaching-record-system that referenced this pull request Jan 29, 2026
Updated [Scrutor](https://github.com/khellang/Scrutor) from 6.1.0 to
7.0.0.

<details>
<summary>Release notes</summary>

_Sourced from [Scrutor's
releases](https://github.com/khellang/Scrutor/releases)._

## 7.0.0

## What's Changed
* Add Sponsors section to README by @​khellang in
khellang/Scrutor#255
* Update to .NET 10 by @​khellang in
khellang/Scrutor#265
* Add NuGet packaging and GitHub Packages upload to CI by @​khellang in
khellang/Scrutor#266
* Use MinVer for versioning by @​khellang in
khellang/Scrutor#267
* Add support for service key registration by @​mokarchi in
khellang/Scrutor#262
* Add support for exposing decorated services by @​adamjones2 in
khellang/Scrutor#261
* Add keyed service registration support by @​A-Ebrahimzadeh-dev in
khellang/Scrutor#260

## New Contributors
* @​mokarchi made their first contribution in
khellang/Scrutor#262
* @​adamjones2 made their first contribution in
khellang/Scrutor#261
* @​A-Ebrahimzadeh-dev made their first contribution in
khellang/Scrutor#260

**Full Changelog**:
khellang/Scrutor@v6.1.0...v7.0.0

Commits viewable in [compare
view](khellang/Scrutor@v6.1.0...v7.0.0).
</details>

[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=Scrutor&package-manager=nuget&previous-version=6.1.0&new-version=7.0.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: James Gunn <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants