Skip to content

Add LicenseKeyFactory to supply the license key from DI - #1192

Merged
jbogard merged 3 commits into
mainfrom
license-key-factory
Nov 5, 2026
Merged

jbogard merged 3 commits into
mainfrom
license-key-factory

Conversation

@jbogard

@jbogard jbogard commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Closes #1191.

License keys delivered by a service in the container, such as a secret store client, can't be set during AddMediatR, because no service provider exists yet. This adds a factory just for the key:

services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssemblyContaining<Program>();
    cfg.LicenseKeyFactory = sp => sp.GetRequiredService<ILicenseKeyProvider>().GetMediatRLicense();
});

Why not AddOptions<MediatRServiceConfiguration>(), as the issue proposes

AddMediatR consumes assemblies, behaviors and lifetimes while registering services, so MediatRServiceConfiguration can't be deferred the way AutoMapper defers MapperConfigurationExpression. AutoMapper can do that because its scan assemblies are method arguments, not configuration.

Today the issue's snippet compiles but the key is ignored, which I confirmed with a throwaway app. Honoring it would mean supporting LicenseKey while every other setting on that class silently does nothing when set there. It would also add a Microsoft.Extensions.Options dependency.

The license key is the one setting that can be late: it's only read after the first Mediator is created.

Behavior

  • Threading: the factory runs in LicenseAccessor.Initialize, on the existing background validation thread. Slow work such as a secret store read can't block Mediator construction, which is the path behind the AutoMapper #4640 deadlock.
  • Precedence: LicenseKeyFactory, cfg.LicenseKey, Mediator.LicenseKey, MEDIATR_LICENSE_KEY, then LUCKYPENNY_LICENSE_KEY. A null or blank result falls through to the next source.
  • Provider: it receives the root service provider, so scoped services aren't available.
  • Failures: an exception is logged under the license log category, even if the scope that created the Mediator has been disposed, and doesn't affect Mediator. Validation is scheduled atomically, so the factory isn't retried.
  • Existing gaps fixed here: CheckLicense wasn't atomic, LicenseAccessor assigned its result outside the lock, and the error log could fail with a disposed scope. A slow factory makes all three much easier to hit.
  • Multiple AddMediatR calls: the first configuration wins, the same as LicenseKey today, because the configuration is registered with TryAddSingleton.

IConfigureOptions<> isn't added here. A separate license options type could add it later if there's demand.

Tests

  • New LicenseKeyFactoryTests covers resolving from a container service, precedence over LicenseKey, blank fallback, whitespace stripping, not running during registration, not blocking construction, and logging exceptions, including after the initiating scope is disposed.
  • It also covers calling the factory only once, both for concurrent first Mediator resolutions and for concurrent reads of LicenseAccessor.Current.
  • As regression checks, I temporarily undid each of these and confirmed tests fail: background validation, atomic scheduling, assigning _license inside the lock, and getting the logger before scheduling.
  • MediatR.Tests 277 passed / 4 skipped (15 repeat runs, same result), DependencyInjectionTests 107/107 (net10.0, macOS). net472 runs in Windows CI.
  • No test uses a genuine license: keys are malformed or have bad signatures, and which log message appears shows which key was used.

🤖 Generated with Claude Code

MediatRServiceConfiguration can't be deferred into IOptions because scanning
and registration consume it before a service provider exists. The license key
is only read later, on the background validation thread, so it can come from a
container service through a factory.

The factory runs inside LicenseAccessor.Initialize, keeping slow work such as
secret store reads off the Mediator construction path (AutoMapper #4640).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 5, 2026 16:11
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-05T20:54:15.522855Z a7ef72d New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

License validation scheduling is non-atomic, allowing duplicate factory calls and retries after failure, while error logging can throw after the initiating scope is disposed and fault the background task.

2 open issues
What changed in this PR

Adds LicenseKeyFactory so MediatR can obtain license keys from dependency-injection services after registration, addressing the use case in #1191 without deferring the full configuration.

Changes:

  • Adds a factory receiving the root service provider and integrates it into background license initialization.
  • Gives factory results precedence over existing key sources, with blank-value fallback.
  • Documents usage and adds tests for resolution, precedence, normalization, threading, and exceptions.
File Description
test/​MediatR.Tests/​Licensing/​LicenseKeyFactoryTests.cs Adds factory behavior and background-execution tests.
src/​MediatR/​Registration/​ServiceRegistrar.cs Passes the service provider to the license accessor.
src/​MediatR/​MicrosoftExtensionsDI/​MediatrServiceConfiguration.cs Exposes and documents LicenseKeyFactory.
src/​MediatR/​Licensing/​LicenseAccessor.cs Evaluates the factory before other license key sources.
README.md Documents factory usage, constraints, and precedence.

Review effort: Balanced

ILicenseKeyProvider read like a type that ships with MediatR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…posed

Concurrent first Mediator resolutions could each start validation, and a
thread waiting on the LicenseAccessor lock could create the license again
because the result was assigned after the lock was released. Either way, the
factory could run more than once.

The catch in ValidateLicense also resolved ILoggerFactory from the provider
that created the Mediator. With a disposed request scope, that threw inside the
catch, losing the error and faulting the background task. Get the logger before
starting validation instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain for the dependency-injected license key factory changes.

2 open issues

Review effort: Balanced

@jbogard
jbogard merged commit 771a5ae into main Nov 5, 2026
7 checks passed
@jbogard
jbogard deleted the license-key-factory branch November 5, 2026 22:06
This was referenced Nov 16, 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.

MediatR license key configuration

2 participants