Skip to content

Commit

Permalink
Merge pull request #50 from mayuanyang/responseHandling
Browse files Browse the repository at this point in the history
Unify response middleware can now handle request/response
  • Loading branch information
mayuanyang committed Jan 22, 2022
2 parents be97f97 + 2c07dfe commit 326b86b
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Mediator.Net.TestUtil/Messages/GetGuidResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ namespace Mediator.Net.TestUtil.Messages
public class GetGuidResponse : IResponse
{
public Guid Id { get; }

public string ToBeSetByMiddleware { get; set; }

public GetGuidResponse(Guid id)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Mediator.Net.Context;
using Mediator.Net.Contracts;
using Mediator.Net.Pipeline;
using Mediator.Net.TestUtil.TestUtils;

namespace Mediator.Net.TestUtil.Middlewares
{
public static class ChangeRequestResultMiddleware
{
public static void UseChangeRequestResultMiddleware<TContext>(this IPipeConfigurator<TContext> configurator)
where TContext : IContext<IMessage>
{
configurator.AddPipeSpecification(new ChangeRequestResultMiddlewareSpecification<TContext>());
}
}

public class ChangeRequestResultMiddlewareSpecification<TContext> : IPipeSpecification<TContext>
where TContext : IContext<IMessage>
{
public bool ShouldExecute(TContext context, CancellationToken cancellationToken)
{
return true;
}

public Task BeforeExecute(TContext context, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}

public Task Execute(TContext context, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}

public Task AfterExecute(TContext context, CancellationToken cancellationToken)
{
(context.Result as dynamic).ToBeSetByMiddleware = "i am from middleware";
return Task.CompletedTask;
}


public Task OnException(Exception ex, TContext context)
{
RubishBox.Rublish.Add(ex);
ExceptionDispatchInfo.Capture(ex).Throw();
throw ex;
}
}
}
1 change: 1 addition & 0 deletions src/Mediator.Net/Pipeline/RequestPipe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public async Task<object> Connect(TContext context, CancellationToken cancellati
await _specification.Execute(context, cancellationToken).ConfigureAwait(false);
result = await (Next?.Connect(context, cancellationToken) ??
ConnectToHandler(context, cancellationToken)).ConfigureAwait(false);
context.Result = result;
await _specification.AfterExecute(context, cancellationToken).ConfigureAwait(false);
}
catch (TargetInvocationException e)
Expand Down

0 comments on commit 326b86b

Please sign in to comment.