I am trying to execute a request and return a response with 2 executers, using the Polly library with the Fallback policy. Here is my code so far:
private IExecuter primary;
private IExecuter secondary;
private readonly Policy _policy;
public Client()
{
primary = new Executer("primary");
secondary = new Executer("secondary");
_policy = Policy
.Handle<Exception>()
.Fallback((request) => GetResponseFallback(request));
}
public Response Process(Request request)
{
return _policy.Execute( GetResponse(request));
}
private Response GetResponse(Request request)
{
return this.primary.Execute(request);
}
private Response GetResponseFallback(Request request)
{
return secondary.Execute(request);
}
The problem with this code is that I can't put a Request parameter on this line:
.Fallback((request) => GetResponseFallback(request));
And the code won't compile, because of the error:
"cannot convert from 'System.Threading.CancellationToken' to 'PollyPOC.Request'"
How to make the code compile and tell the fallback policy that the action will receive a Request parameter to the GetResponseFallback action?
In order to pass data to your Fallback method you need to take advantage of the Context
For the sake of simplicity let me simplify your implementation a bit to show you how to use the
Context:So I've just get rid of the
IExecuter,RequestandResponseconcepts to keep the sample code as simple as possible.To pass data to your
GetResponseFallbackwe need to change the parameter like this:So, we have retrieved the
requestdata from theContext. Now we need to somehow pass that information to theGetResponseFallbackcall.The good thing is that we don't need to modify the
GetResponse. On the other hand we need to adjust theProcessmethod like this:contextDatadictionary to store the input parameter in itAction<Context> fallbackActionparameteronFallbackthat's why I defined that like this(_,__) => { }GetResponsedirectly that's why we can use here the discard operator(_) => GetResponse(...)One last important thing: I had to change the
_policyvariable type toPolicy<int>to indicate the return type.For the sake of completeness here is the full source code: