Skip to content

Property interception

SERKAN edited this page Oct 6, 2020 · 2 revisions
public interface IRocket
{
    string Name { get; set; }
    double Fuel { get; set; }

    void Launch();
}

[Intercept(typeof(IRocket))]
public class Rocket: IRocket
{
    [CheckFuel]
    public double Fuel { get; set; }
    public string Name { get; set; }

    public void Launch()
    {
        System.Console.WriteLine("Launching rocket in 3...2.....1 🚀");
    }
}

public class CheckFuelAttribute: PropertyInterceptorAttribute
{

}

[InterceptFor(typeof(CheckFuelAttribute))]
public class CheckFuelInterceptor: PropertyInterceptor
{
    private readonly Logger logger;
    public CheckFuelInterceptor(Logger logger)
    {
        this.logger = logger;
    }

    // PropertyInterceptor class provides OnGet and OnSet methods.
    // These methods will be called before the actual method.
    public override Task OnSet(IInvocation invocation, object value)
    {
        var hasEnoughFuel = (double) value > 70d;

        if (!hasEnoughFuel)
            throw new System.Exception("Fuel is not enough to launch.");

        logger.LogInfo($"[CheckFuel] Fuel: %{value}, enough to launch.");

        return Task.FromResult(Task.CompletedTask);
    }
}
Clone this wiki locally