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

Full source code here.

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.

public class BreweryController : Controller
{
	private readonly IHttpClientFactory _httpClientFactory;
	private readonly IPolicyRegistry<string> _policyRegistry;
	public BreweryController(IHttpClientFactory httpClientFactory, IPolicyRegistry<string> policyRegistry)
	{
		_policyRegistry = policyRegistry;
		_httpClientFactory = httpClientFactory;
	}

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

var simmyPolicy = _policyRegistry.GetRandomChaosPolicy<AsyncMonkeyPolicy<HttpResponseMessage>>();
//snip..
var 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.

Leave a Reply

Your email address will not be published. Required fields are marked *