Simmy Chaos Engine for .NET – Part 7, Using a Random Chaos Policy

Full source code here.

Want to learn more about Polly? Check out my Pluralsight course on it.

This post builds on the previous one where I added chaos policies to a registry and dynamically configured their settings via a config file. In that example the chaos policy used was hard coded within the action method.

In this example the chaos policy will be chosen randomly from the available ones.

To accomplish this I have added an extension method to the Polly registry class. This method randomly chooses a chaos policy from the registry, you can find the source code from this in the attached file, it is not just a proof of concept and not designed to be robust.

Inside the controller the constructor remains the same as in the previous post.

1public class BreweryController : Controller
3	private readonly IHttpClientFactory _httpClientFactory;
4	private readonly IPolicyRegistry<string> _policyRegistry;
5	public BreweryController(IHttpClientFactory httpClientFactory, IPolicyRegistry<string> policyRegistry)
6	{
7		_policyRegistry = policyRegistry;
8		_httpClientFactory = httpClientFactory;
9	}

The action method then uses the registry extension method to choose a policy and make a request with the chaos policy.

1var simmyPolicy = _policyRegistry.GetRandomChaosPolicy<AsyncMonkeyPolicy<HttpResponseMessage>>();
3var response =  await simmyPolicy.ExecuteAsync(async () => await httpClient.GetAsync(requestEndpoint));

If this is of use to you, you could consider adding another extension method to the registry to wrap multiple chaos policies together.

Full source code here.

comments powered by Disqus