Skip to content

Adding context

Josh Hiles edited this page Dec 22, 2023 · 1 revision

Results aren't very useful without some way to identify them. Use the AddContext method to add to the context for an experiment:

public IUser GetUserByName(string userName)
{
    return Scientist.Science<IUser>("get-user-by-name", experiment =>
    {
        experiment.AddContext("username", userName);

        experiment.Use(() => FindUser(userName));
        experiment.Try(() => GetUser(userName));
    });
}

AddContext takes a string identifier and an object value, and adds them to an internal Dictionary. When you publish the results, you can access the context by using the Contexts property:

public class MyResultPublisher : IResultPublisher
{
    public Task Publish<T, TClean>(Result<T, TClean> result)
    {
        foreach (var kvp in result.Contexts)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
        return Task.FromResult(0);
    }
}

Clone this wiki locally