jeudi 4 mai 2017

Fluent API Method Call Chain - Use Reflection and Attributes to handle calls (C#)

I have a fluent API which I am trying to add another implementation for by passing in an enum to determine which object will be created and delegated to behind the scenes. It's for a UI testing framework, the fluent calls look like this:

CreateSomeBrowserObjectWrapper( BrowserType.NewImplementation )
        .Click( x => x.FindByCssSelector( "someCssSelector" ) )
        .EnterTextIntoDialogBox( "some text" )
        .Assert( b => b.PageContains( "good job! you clicked the button and entered: 'some text'" ) );

The different implementations behave very differently. One can handle each call being made as the caller requests it but another needs to cache calls and then only perform them when certain conditions are met. In this example my problem implementation would need to cache the click and then pass the lambda to the call behind EnterTextIntoDialogBox(..) to do that all in one go. BUT not in every case, because the order of the chained calls and the call types is what determines that they need to be cached or not. Just clicking the element alone would be fine, that could be done as the caller invokes it.

What I am thinking is to try to add attributes to my methods behind the scenes:

[NonChainable]
public T EnterTextIntoDialogBox( string text )
{
    //do stuff
    return this as T;
}

And then use reflection somehow to analyse the fluent method call chain to see if anything called has this attribute and if so then I will handle them entire chain differently.

I cannot fathom how to go about this - does anyone have any ideas?





Aucun commentaire:

Enregistrer un commentaire