public async Task Can_Integrate_With_Polly_Policies_Async() { var pollyPolicy = Policy .Handle <CustomException>() .CircuitBreakerAsync( exceptionsAllowedBeforeBreaking: 2, durationOfBreak: TimeSpan.FromSeconds(1)); var policy = MiddlewareBuilder.BuildAsync( new PollyMiddleware <string, int>(pollyPolicy)); var calledCount = 0; await Assert.ThrowsAsync <CustomException>(async() => await policy.RunAsync("context", ct => { calledCount++; throw new CustomException(); }, CancellationToken.None)); await Assert.ThrowsAsync <CustomException>(async() => await policy.RunAsync("context", ct => { calledCount++; throw new CustomException(); }, CancellationToken.None)); await Assert.ThrowsAsync <BrokenCircuitException>(async() => await policy.RunAsync("context", ct => { calledCount++; throw new CustomException(); }, CancellationToken.None)); calledCount.ShouldBe(2); }
public async Task PolicyBuilder_Async() { var called = false; var noop = MiddlewareBuilder.BuildAsync <string, int>(); var result = await noop.RunAsync("context", async ct => { called = true; await Task.Delay(5, ct); return(1); }, CancellationToken.None); called.ShouldBeTrue(); result.ShouldBe(1); }
public async Task MiddlewareBuilder_Error_Handler_Async() { var called = false; var noop = MiddlewareBuilder.BuildAsync( new ErrorHandlingMiddleware <string, int, InvalidOperationException>()); var result = await noop.RunAsync("context", async ct => { called = true; await Task.Delay(5, ct); throw new InvalidOperationException(); }, CancellationToken.None); called.ShouldBeTrue(); result.ShouldBe(0); }
/// <summary> /// Produces a callable middleware chain from the configured middlewares. /// /// </summary> /// <returns>A callable <see cref="HandleMessageMiddleware"/></returns> public HandleMessageMiddleware Build() { _configure?.Invoke(this); // We reverse the middleware array so that the declaration order matches the execution order // (i.e. russian doll). var middlewares = _middlewares .Select(m => m()) .Reverse() .ToList(); if (_handlerMiddleware != null) { // Handler middleware needs to be last in the chain, so we keep an explicit reference to // it and add it here middlewares.Insert(0, _handlerMiddleware); } return(MiddlewareBuilder.BuildAsync(middlewares.ToArray())); }