Introduction
When developing Dynamics 365 plugins, there are many scenarios where data calculated in one plugin step needs to be accessed in another step within the same execution pipeline.
For example, you may calculate a customer risk score in a Pre-Operation plugin and need to use the same value later in a Post-Operation plugin. Without a mechanism to share data between plugin steps, developers often resort to unnecessary database queries, custom entities, or complex workarounds.
This is where Shared Variables become extremely useful.
Shared Variables provide a lightweight and efficient way to pass information between plugin steps participating in the same execution pipeline. They help reduce duplicate calculations, minimize database calls, and improve the overall performance of your Dynamics 365 solution.
In this article, we’ll explore how Shared Variables work, when to use them, practical implementation examples, common mistakes, and best practices every Dynamics 365 developer should know.
π Related Article
Before working with Shared Variables, it is important to understand how plugin stages execute within the Dynamics 365 event framework. Read our detailed guide on Dynamics 365 Plugin Execution Pipeline.
What Are Shared Variables in Dynamics 365 Plugins?
Shared Variables are a collection of key-value pairs available through the IPluginExecutionContext object.
They allow one plugin step to store information that can later be accessed by another plugin step executing within the same operation pipeline.
Think of Shared Variables as temporary storage that exists only for the duration of the current transaction.
A plugin can write data into Shared Variables:
context.SharedVariables["CustomerType"] = "Premium";
Later, another plugin step can retrieve the same value:
string customerType =
context.SharedVariables["CustomerType"].ToString();
Unlike data stored in Dataverse, Shared Variables are not persisted to the database. Once the operation completes, the values are discarded.
Why Use Shared Variables?
Many developers initially solve communication problems between plugin steps by performing additional database queries.
Consider the following example:
Pre-Operation Plugin
β
Calculate Risk Score
β
Store Risk Score in Dataverse
β
Post-Operation Plugin
β
Retrieve Risk Score Again
Although this approach works, it introduces unnecessary database operations.
A better approach is:
Pre-Operation Plugin
β
Calculate Risk Score
β
Store in Shared Variables
β
Post-Operation Plugin
β
Read Shared Variable
This approach offers several advantages:
- Eliminates unnecessary database queries
- Improves plugin performance
- Reduces complexity
- Keeps business logic cleaner
- Simplifies maintenance
For heavily customized environments, these performance improvements can have a noticeable impact.
How Shared Variables Work
Shared Variables are stored inside the current plugin execution context.
The collection behaves similarly to a dictionary where each entry contains:
- A unique key
- A corresponding value
Example:
context.SharedVariables["RiskScore"] = 85;
The value can later be retrieved using the same key:
int riskScore =
(int)context.SharedVariables["RiskScore"];
Since the data is stored in memory during the current execution pipeline, access is extremely fast compared to retrieving data from Dataverse.
Plugin Execution Flow with Shared Variables
The following diagram illustrates how Shared Variables can be used across plugin stages.

A common execution flow might look like:
Pre-Validation Plugin
β
Store Shared Variable
β
Pre-Operation Plugin
β
Read Shared Variable
β
Post-Operation Plugin
β
Use Shared Variable Value
Because all steps participate in the same execution pipeline, the data remains available throughout the operation.
Practical Example: Passing Data Between Plugin Steps
Let’s consider a common business requirement.
Scenario
Whenever an Account record is updated:
- Calculate a customer risk score.
- Use the calculated score later during post-processing activities.
Step 1: Store Data in Shared Variables
Inside a Pre-Operation plugin:
int riskScore = CalculateRiskScore();
context.SharedVariables["RiskScore"] =
riskScore;
At this point, the value is available to all subsequent plugin steps participating in the same execution pipeline.
Step 2: Retrieve Data in Another Plugin Step
Inside a Post-Operation plugin:
int riskScore =
(int)context.SharedVariables["RiskScore"];
tracingService.Trace(
$"Calculated Risk Score: {riskScore}"
);
The Post-Operation plugin can immediately access the value without performing additional calculations or database queries.
This pattern is frequently used in enterprise Dynamics 365 implementations to improve performance and reduce code duplication.
Shared Variables vs Pre Images and Post Images
One of the most common areas of confusion for Dynamics 365 developers is understanding when to use Shared Variables versus Pre Images and Post Images.
Although both mechanisms provide access to data during plugin execution, they serve very different purposes.
Use Shared Variables When You Need
- Calculated values
- Flags
- Temporary data
- Communication between plugin steps
- Intermediate processing results
Examples:
context.SharedVariables["Discount"] = 10;
context.SharedVariables["ValidationPassed"] = true;
context.SharedVariables["CustomerSegment"] = "Enterprise";
Use Pre Images and Post Images When You Need
- Original field values
- Updated field values
- Change detection
- Before-and-after comparisons
Examples:
- Previous Account Name
- Previous Credit Limit
- Updated Customer Category
π Related Article
If your goal is to compare values before and after an update operation, read our detailed guide on Pre Image vs Post Image in Dynamics 365.
| Feature | Shared Variables | Pre/Post Images |
|---|---|---|
| Store Custom Data | Yes | No |
| Store Calculated Values | Yes | No |
| Access Entity Values | Limited | Yes |
| Compare Before and After Changes | No | Yes |
| Pass Data Between Plugin Steps | Yes | No |
| Avoid Additional Queries | Yes | Sometimes |
Common Use Cases for Shared Variables
Shared Variables can be applied in many real-world Dynamics 365 scenarios. Let’s look at some of the most common use cases.
1. Passing Calculated Values Between Plugin Steps
This is the most common use case.
Imagine a customer risk score is calculated during the Pre-Operation stage. Instead of recalculating the value later, it can be stored once and reused throughout the execution pipeline.
context.SharedVariables["RiskScore"] = riskScore;
Later:
int riskScore =
(int)context.SharedVariables["RiskScore"];
This approach improves performance and keeps business logic centralized.
2. Passing Validation Results
A validation plugin may determine whether processing should continue.
Example:
context.SharedVariables["ValidationPassed"] = true;
Subsequent plugin steps can read the value and adjust their logic accordingly.
if(context.SharedVariables.Contains("ValidationPassed"))
{
bool validationPassed =
(bool)context.SharedVariables["ValidationPassed"];
}
3. Passing Business Flags
Sometimes plugin logic depends on specific conditions.
Example:
context.SharedVariables["IsVipCustomer"] = true;
Later stages can make decisions based on this information without re-evaluating the business rule.
5. Communication Between Multiple Plugin Steps
Shared Variables act as a communication mechanism between plugin steps participating in the same execution pipeline.
This becomes especially useful in complex enterprise solutions where multiple plugins contribute to a larger business process.
Common Mistakes Developers Make
Although Shared Variables are simple to use, there are several common mistakes developers should avoid.
Mistake 1: Assuming Shared Variables Persist in Dataverse
One of the biggest misconceptions is that Shared Variables are stored permanently.
They are not.
Shared Variables exist only during the current operation.
Once the execution pipeline completes, all Shared Variable data is discarded.
Mistake 2: Using Shared Variables as Long-Term Storage
Shared Variables should never replace:
- Dataverse tables
- Configuration records
- Environment variables
If information needs to persist beyond the current transaction, it should be stored elsewhere.
Mistake 3: Not Checking Whether the Key Exists
Bad example:
var riskScore =
context.SharedVariables["RiskScore"];
If the key does not exist, an exception may occur.
Better approach:
if(context.SharedVariables.Contains("RiskScore"))
{
var riskScore =
context.SharedVariables["RiskScore"];
}
Always verify that the key exists before attempting to access it.
Mistake 4: Storing Large Objects
Shared Variables should remain lightweight.
Avoid storing:
- Large collections
- Massive datasets
- Complex object graphs
Doing so can increase memory consumption and negatively impact performance.
Mistake 5: Using Shared Variables When Pre/Post Images Are More Appropriate
If your goal is to compare values before and after an update, Shared Variables are usually not the correct solution.
For example:
Old Credit Limit
New Credit Limit
This information should typically come from Pre Images and Post Images rather than Shared Variables.
Shared Variables and Plugin Performance
One of the major benefits of Shared Variables is performance optimization.
Every unnecessary operation within a plugin affects overall system performance.
Without Shared Variables:
Plugin A
β
Calculate Value
β
Plugin B
β
Calculate Same Value Again
With Shared Variables:
Plugin A
β
Calculate Value Once
β
Store Shared Variable
β
Plugin B
β
Reuse Existing Value
Benefits include:
- Reduced CPU utilization
- Fewer database calls
- Faster execution times
- Improved scalability
In environments processing thousands of transactions daily, these improvements can become significant.
Shared Variables and Plugin Depth
Shared Variables can also help reduce unnecessary processing in complex plugin chains.
Consider the following scenario:
Plugin Executes
β
Business Logic Runs
β
Plugin Executes Again
Developers sometimes use Shared Variables to track whether processing has already occurred.
Example:
context.SharedVariables["Processed"] = true;
Later:
if(context.SharedVariables.Contains("Processed"))
{
return;
}
This approach can help prevent duplicate processing and simplify execution flow.
However, Shared Variables should not be viewed as a replacement for proper plugin design.
π Related Article
Learn how recursive plugin execution can lead to runtime failures in our guide on Plugin Depth Exceeded Error in Dynamics 365.
Shared Variables and Filtering Attributes
Shared Variables and Filtering Attributes often complement each other.
Filtering Attributes reduce unnecessary plugin executions.
Shared Variables reduce unnecessary processing within those executions.
A well-designed plugin solution typically uses both techniques together.
Example:
Filtering Attributes
β
Reduce Plugin Executions
β
Shared Variables
β
Reduce Duplicate Processing
π Related Article
Learn how to configure plugin steps efficiently in our guide on Filtering Attributes in Dynamics 365 Plugins.
Best Practices for Using Shared Variables
Use Meaningful Keys
Avoid generic names:
context.SharedVariables["Value"]
Prefer descriptive names:
context.SharedVariables["RiskScore"]
context.SharedVariables["CustomerSegment"]
context.SharedVariables["ValidationPassed"]
Keep Data Lightweight
Store only the information necessary for subsequent processing.
Small values perform better and are easier to maintain.
Check Before Reading
Always verify that the key exists:
if(context.SharedVariables.Contains("RiskScore"))
{
// Logic
}
Avoid Unnecessary Database Queries
If data is already available through Shared Variables, reuse it instead of retrieving it again.
Document Shared Variable Usage
When multiple developers work on the same solution, clearly documenting Shared Variable keys helps prevent confusion.
Use Shared Variables Only Within the Current Pipeline
Remember:
Shared Variables
β Permanent Storage
They exist only during the current operation.

Frequently Asked Questions
What are Shared Variables in Dynamics 365 Plugins?
Shared Variables are temporary key-value pairs stored within the Plugin Execution Context that allow plugin steps to exchange information during the same execution pipeline.
When should I use Shared Variables?
Use Shared Variables when data calculated in one plugin step needs to be accessed by another step participating in the same operation.
Do Shared Variables persist in Dataverse?
No. Shared Variables exist only during the current execution and are discarded when the operation completes.
Can Shared Variables improve performance?
Yes. They help eliminate duplicate calculations and unnecessary database queries, resulting in more efficient plugin execution.
What is the difference between Shared Variables and Pre/Post Images?
Shared Variables store custom data and calculated values, while Pre/Post Images provide snapshots of entity data before and after changes.
Can Shared Variables help prevent Plugin Depth issues?
They can help reduce duplicate processing and simplify execution flow, but they should not be used as a substitute for proper plugin design.
Are Shared Variables available across all plugin stages?
Yes, Shared Variables can be accessed by plugin steps participating in the same execution pipeline, provided the data has been stored before it is read.
Conclusion
Shared Variables provide a simple yet powerful mechanism for sharing information between plugin steps in Dynamics 365. They eliminate unnecessary database queries, improve performance, reduce duplicate calculations, and help developers build cleaner and more maintainable solutions.
Understanding when to use Shared Variablesβand when to use alternatives such as Pre/Post Imagesβis an important skill for every Dynamics 365 developer.
When combined with a solid understanding of the Plugin Execution Pipeline, Filtering Attributes, and proper plugin design principles, Shared Variables become an essential tool for building scalable and high-performing Dynamics 365 applications.