Shared variables in Dynamics 365 plugins are essentially global variables that are accessible across all plugin steps and instances. These variables can be used to store data that needs to be shared across different steps of the plugin or across different instances of the same plugin.
Using shared variables in Dynamics 365 plugins provides several benefits. First, it allows you to share data across different plugin steps and instances, which can be very useful if you need to process multiple records in a batch or if you have complex logic that requires data to be shared across different steps. Second, shared variables can help you optimize your plugin performance by reducing the need to retrieve data from the database multiple times. Finally, shared variables can simplify your plugin code by reducing the need to pass data between different methods or classes.
To use the shared variable, you can simply reference it within your plugin code. For example, if you want to increment the counter every time your plugin executes, you can do this:
Generally, you may have different plugins run for the same entity in different orders. If you want to check whether a plugin has performed a certain logic during its execution, you can set a shared variable and then read it in another plugin, as shown below.
Setting shared variable first time:
Reading it another plugin: