-
Notifications
You must be signed in to change notification settings - Fork 347
Add a resolve middleware example #41
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
src/MiddlewarePipelineExample/Middleware/ActivationAuditMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| using Autofac.Core.Resolving.Pipeline; | ||
|
|
||
| namespace MiddlewarePipelineExample.Middleware; | ||
|
|
||
| /// <summary> | ||
| /// Applied to every registration in the container rather than named on each one. | ||
| /// This is the answer to wanting a hook that runs for all registered components | ||
| /// without calling an extension method on each registration in turn. | ||
| /// </summary> | ||
| public sealed class ActivationAuditMiddleware : IResolveMiddleware | ||
| { | ||
| private readonly List<string> _log; | ||
|
|
||
| public ActivationAuditMiddleware(List<string> log) => _log = log; | ||
|
|
||
| public PipelinePhase Phase => PipelinePhase.RegistrationPipelineStart; | ||
|
|
||
| public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> next) | ||
| { | ||
| next(context); | ||
|
|
||
| // The instance is available after next() returns, because that is when | ||
| // the rest of the pipeline has run and activation has happened. | ||
| if (context.NewInstanceActivated) | ||
| { | ||
| _log.Add(context.Instance!.GetType().Name); | ||
| } | ||
| } | ||
| } |
33 changes: 33 additions & 0 deletions
33
src/MiddlewarePipelineExample/Middleware/CachingMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| using Autofac.Core.Resolving.Pipeline; | ||
|
|
||
| namespace MiddlewarePipelineExample.Middleware; | ||
|
|
||
| /// <summary> | ||
| /// Short-circuits the pipeline. Setting <see cref="ResolveRequestContext.Instance"/> | ||
| /// and never calling <c>next</c> means activation is skipped entirely, so nothing | ||
| /// downstream runs. Useful for a cache, and the reason middleware can be cheaper | ||
| /// than a registration that has to construct something to decide it wasn't needed. | ||
| /// </summary> | ||
| public sealed class CachingMiddleware : IResolveMiddleware | ||
| { | ||
| private readonly Action<string> _report; | ||
| private object? _cached; | ||
|
|
||
| public CachingMiddleware(Action<string> report) => _report = report; | ||
|
|
||
| public PipelinePhase Phase => PipelinePhase.ResolveRequestStart; | ||
|
|
||
| public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> next) | ||
| { | ||
| if (_cached is not null) | ||
| { | ||
| _report($"cache hit for {context.Service}, activation skipped"); | ||
| context.Instance = _cached; | ||
| return; | ||
| } | ||
|
|
||
| next(context); | ||
| _cached = context.Instance; | ||
| _report($"cache miss for {context.Service}, instance stored"); | ||
| } | ||
| } |
26 changes: 26 additions & 0 deletions
26
src/MiddlewarePipelineExample/Middleware/CorrelationIdMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| using Autofac; | ||
| using Autofac.Core.Resolving.Pipeline; | ||
|
|
||
| namespace MiddlewarePipelineExample.Middleware; | ||
|
|
||
| /// <summary> | ||
| /// Injects ambient state into a resolve without every caller having to pass it. | ||
| /// The parameter has to be added before the constructor is chosen, which is why | ||
| /// this sits in the parameter selection phase. | ||
| /// </summary> | ||
| public sealed class CorrelationIdMiddleware : IResolveMiddleware | ||
| { | ||
| private readonly Func<string> _currentCorrelationId; | ||
|
|
||
| public CorrelationIdMiddleware(Func<string> currentCorrelationId) => _currentCorrelationId = currentCorrelationId; | ||
|
|
||
| public PipelinePhase Phase => PipelinePhase.ParameterSelection; | ||
|
|
||
| public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> next) | ||
| { | ||
| context.ChangeParameters( | ||
| context.Parameters.Concat([new NamedParameter("correlationId", _currentCorrelationId())])); | ||
|
|
||
| next(context); | ||
| } | ||
| } |
26 changes: 26 additions & 0 deletions
26
src/MiddlewarePipelineExample/Middleware/RootScopeGuardMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| using Autofac.Core; | ||
| using Autofac.Core.Lifetime; | ||
| using Autofac.Core.Resolving.Pipeline; | ||
|
|
||
| namespace MiddlewarePipelineExample.Middleware; | ||
|
|
||
| /// <summary> | ||
| /// Fails fast with a readable message when a service that expects a unit of work | ||
| /// is resolved straight from the root scope, where it would be captured for the | ||
| /// lifetime of the application. | ||
| /// </summary> | ||
| public sealed class RootScopeGuardMiddleware : IResolveMiddleware | ||
| { | ||
| public PipelinePhase Phase => PipelinePhase.ScopeSelection; | ||
|
|
||
| public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> next) | ||
| { | ||
| if (Equals(context.ActivationScope.Tag, LifetimeScope.RootTag)) | ||
| { | ||
| throw new DependencyResolutionException( | ||
| $"{context.Service} must be resolved from a child lifetime scope, not the root container."); | ||
| } | ||
|
|
||
| next(context); | ||
| } | ||
| } |
26 changes: 26 additions & 0 deletions
26
src/MiddlewarePipelineExample/Middleware/TimingMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| using System.Diagnostics; | ||
| using Autofac.Core.Resolving.Pipeline; | ||
|
|
||
| namespace MiddlewarePipelineExample.Middleware; | ||
|
|
||
| /// <summary> | ||
| /// Measures how long a resolve takes. Attached as service middleware, so it runs | ||
| /// for every resolve of the service regardless of which registration answers it. | ||
| /// </summary> | ||
| public sealed class TimingMiddleware : IResolveMiddleware | ||
| { | ||
| private readonly Action<string> _report; | ||
|
|
||
| public TimingMiddleware(Action<string> report) => _report = report; | ||
|
|
||
| public PipelinePhase Phase => PipelinePhase.ResolveRequestStart; | ||
|
|
||
| public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> next) | ||
| { | ||
| var stopwatch = Stopwatch.StartNew(); | ||
| next(context); | ||
| stopwatch.Stop(); | ||
|
|
||
| _report($"{context.Service} took {stopwatch.ElapsedMilliseconds}ms"); | ||
| } | ||
| } |
13 changes: 13 additions & 0 deletions
13
src/MiddlewarePipelineExample/MiddlewarePipelineExample.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Autofac" Version="9.3.2" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| using Autofac; | ||
| using Autofac.Core; | ||
| using MiddlewarePipelineExample.Middleware; | ||
| using MiddlewarePipelineExample.Services; | ||
|
|
||
| namespace MiddlewarePipelineExample; | ||
|
|
||
| internal static class Program | ||
| { | ||
| /// <summary> | ||
| /// Runs each scenario in turn. They are independent, so they each build their | ||
| /// own container rather than sharing one. | ||
| /// </summary> | ||
| public static void Main() | ||
| { | ||
| AuditEveryRegistration(); | ||
| TimeAResolve(); | ||
| ShortCircuitWithACache(); | ||
| InjectAmbientState(); | ||
| RejectRootScopeResolves(); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Attaches middleware to every registration at once, without naming it on | ||
| /// each one. Autofac issue #1337 asked for exactly this hook. | ||
| /// </summary> | ||
| private static void AuditEveryRegistration() | ||
| { | ||
| Header("Middleware on every registration"); | ||
|
|
||
| var activated = new List<string>(); | ||
| var builder = new ContainerBuilder(); | ||
|
|
||
| builder.ComponentRegistryBuilder.Registered += (sender, args) => | ||
| args.ComponentRegistration.PipelineBuilding += (sender2, pipeline) => | ||
| pipeline.Use(new ActivationAuditMiddleware(activated)); | ||
|
|
||
| builder.RegisterType<ReportService>().As<IReportService>(); | ||
| builder.RegisterType<ScopedResource>().As<IScopedResource>(); | ||
|
|
||
| using var container = builder.Build(); | ||
| using var scope = container.BeginLifetimeScope(); | ||
| scope.Resolve<IReportService>(); | ||
| scope.Resolve<IScopedResource>(); | ||
|
|
||
| Console.WriteLine($" activated: {string.Join(", ", activated)}"); | ||
| Console.WriteLine(" neither registration mentions the middleware."); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Service middleware wraps every resolve of a service, so it can measure what | ||
| /// activation actually costs without the service or its registration knowing. | ||
| /// </summary> | ||
| private static void TimeAResolve() | ||
| { | ||
| Header("Timing a resolve"); | ||
|
|
||
| var builder = new ContainerBuilder(); | ||
| builder.RegisterType<SlowService>().As<ISlowService>(); | ||
| builder.RegisterServiceMiddleware<ISlowService>(new TimingMiddleware(m => Console.WriteLine($" {m}"))); | ||
|
|
||
| using var container = builder.Build(); | ||
| using var scope = container.BeginLifetimeScope(); | ||
| scope.Resolve<ISlowService>(); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Setting <c>Instance</c> and returning without calling <c>next</c> ends the | ||
| /// pipeline early, so activation never happens. That is what makes a middleware | ||
| /// cache cheaper than a registration which has to construct something before it | ||
| /// can decide the work was unnecessary. | ||
| /// </summary> | ||
| private static void ShortCircuitWithACache() | ||
| { | ||
| Header("Short-circuiting the pipeline"); | ||
|
|
||
| var builder = new ContainerBuilder(); | ||
| builder.RegisterType<SlowService>().As<ISlowService>(); | ||
| builder.RegisterServiceMiddleware<ISlowService>(new CachingMiddleware(m => Console.WriteLine($" {m}"))); | ||
|
|
||
| using var container = builder.Build(); | ||
| for (var i = 0; i < 2; i++) | ||
| { | ||
| using var scope = container.BeginLifetimeScope(); | ||
| scope.Resolve<ISlowService>(); | ||
| } | ||
|
|
||
| Console.WriteLine(" the second resolve never reached activation."); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Supplies a constructor argument no caller passes. Watch which pipeline this | ||
| /// one attaches to: parameter selection belongs to the registration pipeline, so | ||
| /// service middleware is rejected outright. | ||
| /// </summary> | ||
| private static void InjectAmbientState() | ||
| { | ||
| Header("Injecting ambient state"); | ||
|
|
||
| var correlationId = "req-001"; | ||
| var builder = new ContainerBuilder(); | ||
|
|
||
| // Parameter selection is a registration pipeline phase, so this one goes | ||
| // on the registration. Adding it as service middleware throws, because a | ||
| // service pipeline has already finished by the time parameters matter. | ||
| builder.RegisterType<RequestHandler>() | ||
| .As<IRequestHandler>() | ||
| .ConfigurePipeline(pipeline => pipeline.Use(new CorrelationIdMiddleware(() => correlationId))); | ||
|
|
||
| using var container = builder.Build(); | ||
|
|
||
| using (var scope = container.BeginLifetimeScope()) | ||
| { | ||
| Console.WriteLine($" {scope.Resolve<IRequestHandler>().Describe()}"); | ||
| } | ||
|
|
||
| correlationId = "req-002"; | ||
| using (var scope = container.BeginLifetimeScope()) | ||
| { | ||
| Console.WriteLine($" {scope.Resolve<IRequestHandler>().Describe()}"); | ||
| } | ||
|
|
||
| Console.WriteLine(" no caller passed the correlation id."); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Turns a captured dependency into an immediate, readable failure. Resolving a | ||
| /// per-scope service straight from the root container would otherwise keep it | ||
| /// alive for the life of the application, and the symptom usually shows up a | ||
| /// long way from the cause. | ||
| /// </summary> | ||
| private static void RejectRootScopeResolves() | ||
| { | ||
| Header("Failing fast on a root scope resolve"); | ||
|
|
||
| var builder = new ContainerBuilder(); | ||
| builder.RegisterType<ScopedResource>().As<IScopedResource>().InstancePerLifetimeScope(); | ||
| builder.RegisterServiceMiddleware<IScopedResource>(new RootScopeGuardMiddleware()); | ||
|
|
||
| using var container = builder.Build(); | ||
|
|
||
| using (var scope = container.BeginLifetimeScope()) | ||
| { | ||
| Console.WriteLine($" from a child scope: {scope.Resolve<IScopedResource>().Use()}"); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| container.Resolve<IScopedResource>(); | ||
| } | ||
| catch (DependencyResolutionException ex) | ||
| { | ||
| Console.WriteLine($" from the root scope: {ex.Message.Split(" ---> ")[^1]}"); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Writes a section title so each scenario's output is easy to tell apart. | ||
| /// </summary> | ||
| private static void Header(string title) | ||
| { | ||
| Console.WriteLine(); | ||
| Console.WriteLine(title); | ||
| Console.WriteLine(new string('-', title.Length)); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| # MiddlewarePipelineExample | ||
|
|
||
| Five things resolve middleware is actually useful for, each in its own class: auditing every registration without naming the middleware on any of them, timing a resolve, short-circuiting the pipeline from a cache, injecting ambient state as a parameter, and rejecting a resolve that came from the root scope. | ||
|
|
||
| The correlation ID scenario is the one worth reading twice. It runs in the parameter selection phase, which belongs to the registration pipeline, so it has to be attached with `ConfigurePipeline` rather than `RegisterServiceMiddleware`. Registering it as service middleware throws, and that error is the clearest explanation of why Autofac has two pipelines rather than one. | ||
|
|
||
| Packages: [`Autofac`](https://github.com/autofac/Autofac) | ||
|
|
||
| Run `dotnet run --project src/MiddlewarePipelineExample`. Each scenario prints a short section showing what the middleware did. | ||
|
|
||
| See [Resolve Pipelines](https://autofac.readthedocs.io/en/latest/advanced/pipelines.html) for the documentation this example follows. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| namespace MiddlewarePipelineExample.Services; | ||
|
|
||
| public interface IReportService | ||
| { | ||
| string Run(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| namespace MiddlewarePipelineExample.Services; | ||
|
|
||
| public interface IRequestHandler | ||
| { | ||
| string Describe(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| namespace MiddlewarePipelineExample.Services; | ||
|
|
||
| public interface IScopedResource | ||
| { | ||
| string Use(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| namespace MiddlewarePipelineExample.Services; | ||
|
|
||
| public interface ISlowService | ||
| { | ||
| string Fetch(); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.