Priority fact factory usage - GetcuReone/FactFactory GitHub Wiki

How to use the priority fact factory

We will analyze how to use the priority fact factory using the example that we considered here.

You can find the complete example code here.

Part 1. Create priority

In order to set the priority, we first need to create a special fact that will indicate the priority. In order not to fool with method implementations, we will take the base class supplied with the library as a basis.

public class Priority1 : UintPriorityBase
{
    public Priority1() : base(1)
    {
    }
}

As simple as that. We have just created a fact indicating priority. Intuitively, you can understand that the higher the priority number, the lower the priority.

Part 2. Add rule with priority

We add a new rule to the existing collection.

// Let's create a higher priority rule. And add the condition that if we have John, then everything should be free for him
(Priority1 p, UserFact userFact, MovieFact movieFact, UserEmailFact email) =>
{
    if (email == "[email protected]")
        return new MovieDiscountFact(movieFact.Value.Cost);

    int result = 0;

    var dicounts = DiscountDB.Where(dicount => dicount.UserId == userFact.Value.Id && dicount.MovieId == movieFact.Value.Id).ToList();

    if (dicounts != null)
    {
        foreach(var dicount in dicounts)
        {
            result += dicount.MovieDiscount;
        }

        if (result > movieFact.Value.Cost)
            result = movieFact.Value.Cost;
    }

    return new MovieDiscountFact(result);
},

A rule that has no priority is considered less priority than a rule that has priority.

Part 3. Create priority fact factory

PriorityFactFactory Factory;

[TestInitialize]
public void Initialize()
{
    //...

    Factory = new PriorityFactFactory(GetPriorityFacts);
    
    //...
}

private IEnumerable<IFact> GetPriorityFacts(IWantActionContext<WantAction, FactContainer> context)
{
    return new List<IFact>
    {
        new Priority1(),
    };
}

Part 4. Finall.

Add an example that will demonstrate how priority works.

[TestMethod]
[Description("Calculate the cost of a 'My Hero Academia: Heroes Rising' movie for a 'John Cornero' user.")]
public void CalculatingCostBuyingMovie_2()
{
    // We have information about the user's mail and the identifier of the film, what he wants to buy.
    string email = "[email protected]";
    int movieId = 1;

    // Let's tell the factory what we know
    var container = new FactContainer
    {
        new UserEmailFact(email),
        new MovieIdFact(movieId),
    };

    // We ask the factory to calculate the cost of buying a movie for our user.
    int price = Factory.DeriveFact<MoviePurchasePriceFact>(container).Value;

    // For this user, the discount for this movie is not configured. Therefore we expect full value.
    Assert.AreEqual(0, price, "Everything should be free for John.");
}
⚠️ **GitHub.com Fallback** ⚠️