Skip to content

Add support for keyed DI services (Issue #165)#185

Closed
avgalex wants to merge 1 commit intomicro-elements:masterfrom
avgalex:feature/issue-165-keyed-services
Closed

Add support for keyed DI services (Issue #165)#185
avgalex wants to merge 1 commit intomicro-elements:masterfrom
avgalex:feature/issue-165-keyed-services

Conversation

@avgalex
Copy link
Member

@avgalex avgalex commented Feb 14, 2026

Summary

  • Validators registered via AddKeyedScoped, AddKeyedTransient, AddKeyedSingleton are now discovered automatically
  • Registration order independent — works regardless of whether AddFluentValidationRulesToSwagger() is called before or after keyed validators are registered
  • Graceful fallback when keyed services are not used or DI container doesn't support IKeyedServiceProvider
  • Deduplication: same validator registered as both keyed and non-keyed is returned only once
  • Version bumped to 7.0.4-beta.2

How it works

  1. AddFluentValidationRulesToSwagger() registers IServiceCollection as a singleton snapshot
  2. At resolution time, GetValidators() first resolves non-keyed validators (existing behavior)
  3. Then scans the IServiceCollection snapshot for keyed IValidator<T> descriptors
  4. Resolves each keyed validator via IKeyedServiceProvider.GetKeyedService()
  5. Deduplicates by reference to avoid returning the same validator twice

Files changed

  • ValidatorRegistryExtensions.cs — core resolution logic with new GetKeyedValidators helper
  • ServiceCollectionExtensions.cs (Swashbuckle + NSwag) — register IServiceCollection singleton
  • KeyedServicesTests.cs — 5 tests covering keyed-only, non-keyed regression, mixed, and full integration

Test plan

  • All existing tests pass on net8.0, net9.0, net10.0
  • 5 new keyed services tests pass on all frameworks
  • Manual testing with sample application using keyed validators

Closes #165

🤖 Generated with Claude Code

Validators registered via AddKeyedScoped/Transient/Singleton are now
discovered automatically by scanning IServiceCollection descriptors
and resolving via IKeyedServiceProvider at runtime. This eliminates
registration ordering issues and gracefully falls back when keyed
services are not used.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@avgalex
Copy link
Member Author

avgalex commented Feb 14, 2026

@claude review this PR

@claude
Copy link

claude bot commented Feb 14, 2026

Claude Code is working…

I'll analyze this and get back to you.

View job run

@avgalex
Copy link
Member Author

avgalex commented Feb 14, 2026

Reopening from origin branch to fix CI fetch issue with fork PRs

@avgalex avgalex closed this Feb 14, 2026
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.

Add support for Keyed Services

1 participant