Skip to content

Commit

Permalink
Fix middleware ordering and add a test for the order
Browse files Browse the repository at this point in the history
  • Loading branch information
alistairjevans committed Jul 24, 2022
1 parent 1ddf214 commit 4f75773
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,7 @@ internal static IEnumerable<Type> GenerateAllAutofacMiddleware(IComponentContext
return container.ComponentRegistry.Registrations.SelectMany(r => r.Services)
.OfType<TypedService>()
.Where(s => IsMiddlewareButNotAutofac(s.ServiceType))
.OrderBy(s => container.ComponentRegistry.TryGetServiceRegistration(s, out var reg) ? reg.GetRegistrationOrder() : 0)
.Select(service => typeof(AutofacMiddleware<>).MakeGenericType(service.ServiceType))
.ToArray();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,52 @@ public async void UseAutofacLifetimeScopeInjectorWithExternalScopeDoesNotRegiste
}
}

[Fact]
public void UseAutofacMiddlewareAddsMiddlewareInTheCorrectOrder()
{
var builder = new ContainerBuilder();

var traceSet = new List<Type>();

builder.RegisterType<TracingTestMiddleware<int>>();
builder.RegisterType<TracingTestMiddleware<bool>>();
builder.RegisterType<TracingTestMiddleware<string>>();

var container = builder.Build();
var app = new Mock<IAppBuilder>();
app.Setup(mock => mock.Properties).Returns(new Dictionary<string, object>());
app.Setup(mock => mock.Use(It.IsAny<object>()))
.Callback<object, object[]>((m, _) => traceSet.Add((Type)m));
app.SetReturnsDefault(app.Object);

app.Object.UseAutofacMiddleware(container);

Assert.Collection(
traceSet,
item => Assert.Equal(typeof(AutofacMiddleware<TracingTestMiddleware<int>>), item),
item => Assert.Equal(typeof(AutofacMiddleware<TracingTestMiddleware<bool>>), item),
item => Assert.Equal(typeof(AutofacMiddleware<TracingTestMiddleware<string>>), item));
}

public class TracingTestMiddleware<T> : OwinMiddleware
{
private readonly List<int> _order;
private readonly int _orderNumber;

public TracingTestMiddleware(OwinMiddleware next, List<int> order, int orderNumber)
: base(next)
{
_order = order;
_orderNumber = orderNumber;
}

public override Task Invoke(IOwinContext context)
{
_order.Add(_orderNumber);
return Next.Invoke(context);
}
}

public class TestableLifetimeScope : Disposable, ILifetimeScope
{
public bool ScopeIsDisposed { get; set; }
Expand Down

0 comments on commit 4f75773

Please sign in to comment.