Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@
"stopAtEntry": false,
"type": "coreclr"
},
{
"console": "integratedTerminal",
"cwd": "${workspaceFolder}/src/MiddlewarePipelineExample",
"name": "MiddlewarePipelineExample",
"preLaunchTask": "build",
"program": "${workspaceFolder}/src/MiddlewarePipelineExample/bin/Debug/net10.0/MiddlewarePipelineExample.dll",
"request": "launch",
"stopAtEntry": false,
"type": "coreclr"
},
{
"cwd": "${workspaceFolder}/src/MultitenantExample.AspNetCore",
"launchSettingsProfile": "MultitenantExample.AspNetCore",
Expand Down
1 change: 1 addition & 0 deletions Examples.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<Project Path="src/DotGraphExample/DotGraphExample.csproj" />
<Project Path="src/DynamicProxyExample/DynamicProxyExample.csproj" />
<Project Path="src/GenericHostBuilderExample/GenericHostBuilderExample.csproj" />
<Project Path="src/MiddlewarePipelineExample/MiddlewarePipelineExample.csproj" />
<Project Path="src/MultitenantExample.ConsoleApplication/MultitenantExample.ConsoleApplication.csproj" />
<Project Path="src/PoolingExample/PoolingExample.csproj" />
</Folder>
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Each example has its own README with what it shows and how to run it.
| [DynamicProxyExample](src/DynamicProxyExample/README.md) | Method interception, wired both on the registration and by attribute | [`Autofac.Extras.DynamicProxy`](https://github.com/autofac/Autofac.Extras.DynamicProxy) |
| [PoolingExample](src/PoolingExample/README.md) | Reusing expensive instances across scopes, with a reset-on-return policy | [`Autofac.Pooling`](https://github.com/autofac/Autofac.Pooling) |
| [DotGraphExample](src/DotGraphExample/README.md) | Capturing a resolve operation as a Graphviz graph for troubleshooting | [`Autofac.Diagnostics.DotGraph`](https://github.com/autofac/Autofac.Diagnostics.DotGraph) |
| [MiddlewarePipelineExample](src/MiddlewarePipelineExample/README.md) | Resolve middleware for auditing, timing, caching, ambient state, and scope guards | [`Autofac`](https://github.com/autofac/Autofac) |

### .NET Framework

Expand Down
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 src/MiddlewarePipelineExample/Middleware/CachingMiddleware.cs
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");
}
}
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);
}
}
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 src/MiddlewarePipelineExample/Middleware/TimingMiddleware.cs
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 src/MiddlewarePipelineExample/MiddlewarePipelineExample.csproj
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>
166 changes: 166 additions & 0 deletions src/MiddlewarePipelineExample/Program.cs
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
Comment thread
tillig marked this conversation as resolved.
// 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));
}
}
11 changes: 11 additions & 0 deletions src/MiddlewarePipelineExample/README.md
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.
6 changes: 6 additions & 0 deletions src/MiddlewarePipelineExample/Services/IReportService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace MiddlewarePipelineExample.Services;

public interface IReportService
{
string Run();
}
6 changes: 6 additions & 0 deletions src/MiddlewarePipelineExample/Services/IRequestHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace MiddlewarePipelineExample.Services;

public interface IRequestHandler
{
string Describe();
}
6 changes: 6 additions & 0 deletions src/MiddlewarePipelineExample/Services/IScopedResource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace MiddlewarePipelineExample.Services;

public interface IScopedResource
{
string Use();
}
6 changes: 6 additions & 0 deletions src/MiddlewarePipelineExample/Services/ISlowService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace MiddlewarePipelineExample.Services;

public interface ISlowService
{
string Fetch();
}
Loading
Loading