Context Injection – a clean and maintainable solution for sharing data between steps
In SpecFlow, step definitions are global – steps defined for a single scenario may be bound to step definitions in multiple classes. Sharing data between step definitions when executing a scenario is common. For example, the givenstep can prepare data to be entered and the then step then validates whether the data was entered successfully into the system. If these two step definitions are in the same class, this is pretty easy to handle with instance fields. However, if they are in different classes, sharing the data is trickier. SpecFlow provides a general tag (
ScenarioContext) for scenario-execution-specific data, but this does not really conform to the SOLID principles. Furthermore, if there are multiple values that need to be shared and belong together (e.g. first name and last name), this solution results in glorious spaghetti code. Context injection is here to help!
SpecFlow has a built-in mini dependency injection framework that can resolve dependencies of the binding classes (e.g. classes containing step definitions) provided as constructor parameters. This is called context injection. While it may sound complicated, it is very easy to use: just create your POCOs representing the shared data, and define them as constructor parameters in all binding class that require them.
You can find examples and more details in the documentation.