What Happens During the Dynamics 365 Plug-in Execution Pipeline Stages
When you make custom business logic in Dynamics 365, you use plugins. These plugins run at certain times in a process called the execution pipeline. You can think of this pipeline like an assembly line. Each stage looks at your data or changes it. You should know how each stage works. This helps keep your data safe. It also helps your custom rules work right.
Key Takeaways
Dynamics 365 plug-ins work in a pipeline with four main stages. These stages are Pre-validation, Pre-operation, Main operation, and Post-operation.
Pre-validation checks data before any changes happen. It stops bad actions and keeps your data safe.
Pre-operation lets you change or fix data before saving it. This helps follow business rules and stops mistakes.
Post-operation happens after saving data. It is good for making related records or sending messages. Use asynchronous plug-ins for slow jobs.
Always check plug-in depth so you do not get endless loops. Use debugging tools like Plugin Trace Logs and the Plugin Registration Tool to find and fix problems.
Dynamics 365 Pipeline Stages
Overview
When you change business logic in Dynamics 365, you use the plug-in execution pipeline. The pipeline is like a set of steps. These steps handle your data when you make, change, or remove records. Each stage lets you look at, change, or react to data before or after the main system action. This setup helps you keep your business rules neat and your data safe.
The pipeline is part of Dataverse. It decides how and when your plug-ins work. You can use it to check data, change fields, or send messages. The pipeline makes sure every step happens in the right order.
Stage Order
The pipeline has several stages that always run in the same order. Each stage does something special. Here is the order:
Pre-validation: This is the first stage. It happens before the main system action and outside the database transaction. You can use it to check data and stop the process if something is wrong.
Pre-operation: This is the next stage. It happens inside the database transaction, just before the main action. You can change data here, and if you cancel, the transaction will not finish.
Main Operation: This is the main system action, like saving a record. You cannot add custom plug-ins here, except for special cases.
Post-operation: This stage comes after the main action, still inside the transaction. You can use it to change message details or start other actions. You can also run asynchronous plug-ins here.
The table below shows each stage, its number, and what it does:
You can also see common uses for each stage:
Tip: Plug-ins with a lower order number run first in each stage. If two plug-ins have the same order, the system does not promise which one runs first.
Depth and Context
Plug-in depth shows how many times a plug-in has run in one transaction. Depth starts at 1 the first time your plug-in runs. If your plug-in changes a record and runs again, the depth becomes 2. This helps you stop endless loops. You can check the depth in your code like this:
IPluginExecutionContext context = localContext.PluginExecutionContext;
if (context.Depth > 1)
return;
If you see depth errors, you might have a loop problem. Dynamics 365 has a default depth limit of 8. If your plug-in or workflow runs itself 8 times, the system stops it to keep your data safe. You cannot change this limit online. You need to write your plug-ins to avoid loops.
Developers often see loop problems because the depth counter resets only after a long break.
The system tracks loops using a CorrelationId, so even indirect calls can cause errors.
You should check the depth and avoid changing the same record in your plug-in code.
Quick Reference Table
Here is a table that sums up the pipeline stages:
You can see from the chart that plug-ins add some time to each update. The average time depends on how many plug-ins you use and what they do.
Pre-validation Stage
Timing
The Pre-validation stage happens before the main system action. This stage is outside the database transaction. The system has not checked security yet. No changes have started in the database. You can use this stage to check if the data is correct. For example, you can make sure all needed fields are filled. You can set default values before a record is made or changed. The record does not exist yet, so you cannot use its unique ID.
Actions
You can do many checks in the Pre-validation stage. Here are some common things you can do:
Make sure all required fields have values.
Check if the user can do the action.
Make sure the data follows your business rules.
Stop duplicate records before they get to the database.
Block deleting records if related data is still there.
For example, you may want to stop a user from deleting an account if it has active contacts. You can look for related contacts and show an error if any are found. This stops the deletion before it starts.
Note: If your plugin shows an error in this stage, the system stops right away. No changes happen in the database. No other pipeline stages will run.
The table below shows what you can do in this stage:
Best Practices
You should use the Pre-validation stage for strong checks. This stage lets you set rules before any database changes or security checks. You can also do background actions like sending emails or logging errors. These actions stay in the system even if you block the main action. For example, you can update a log or send a message, then show an error to stop the process. This helps keep your data safe and lets users know what happened.
Here is a sample code for checking plugin depth and stopping more runs:
if (context.Depth > 1)
return; // Stop running again
if (!IsValidData(context.InputParameters))
throw new InvalidPluginExecutionException("Validation failed.");
Tip: Always keep your checks simple and easy to understand. Use this stage to catch problems early and avoid bigger issues later.
Pre-operation Stage
Timing
The Pre-operation stage starts after security checks finish. It happens before the main operation updates the database. You can look at the data and make changes now. This stage is inside the database transaction. If you stop the process here, no changes will save. Use this stage to check if the data is right for the next step.
Data Changes
You can look at and change record values before saving. You can set default values or change fields. You can also change the query to get different records. For example, you can change a RetrieveMultiple request before it runs. This helps you pick which records the system gets. It makes your data work faster.
You can update the target object to change fields before saving. If you see a problem, you can throw an exception to stop the process. This stage lets you catch and fix data or query issues before the main action.
You can use this stage to:
Change the target object to update fields.
Stop the process by throwing an exception.
Change queries to get the right data.
Best Practices
Use the Pre-operation stage to follow business rules and keep data clean. This is a good time to add logic before saving anything. You can set auto IDs, fill in calculated fields, or check for special cases. If your rules are not met, you can block the save and show an error.
Here is a code example for a Pre-operation plugin that updates a field:
public class UpdateAccount : IPlugin { public void Execute(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity entity) { if (entity.LogicalName == "account" && entity.Attributes.Contains("tickersymbol")) { var tickersymbol = entity["tickersymbol"].ToString(); entity["tickersymbol"] = "NYSE: " + tickersymbol; } } } }
You can also set totals or flags on the target entity. This saves time and keeps your process fast.
Tip: Always check your business rules here. If you find a problem, throw an exception to stop the save. This keeps your data safe and your rules strong.
Main Operation and Post-operation
Main Operation
The Main Operation stage is when the system does the main job. It creates, updates, or deletes a record. You cannot add your own plugin code here. The system does this step inside a database transaction. If something goes wrong now or before, the system undoes all changes. You cannot change data in this stage. You must use earlier stages, like Pre-operation, to change data before saving.
The Main Operation stage:
Comes after Pre-operation.
Does the main data change, like saving or deleting.
Does not run custom plugins.
Is part of the database transaction.
Post-operation
The Post-operation stage happens after the Main Operation is done. Now, the system has saved the record. You can use this stage for actions that need the record to exist. For example, you can create related records, send notifications, or call other systems. You can add plugins here to run right away or later.
Here is a simple code example for a post-operation plugin. This plugin makes a task after a new account is created:
public class CreateTaskOnAccountCreate : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.MessageName == "Create" && context.PrimaryEntityName == "account")
{
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(context.UserId);
var task = new Entity("task");
task["subject"] = "Follow up with new account";
task["regardingobjectid"] = new EntityReference("account", context.PrimaryEntityId);
service.Create(task);
}
}
}
Best Practices
Use the Post-operation stage for things that need the record to be saved. Synchronous plugins are good for quick jobs that must finish before the user sees the result. For big or slow jobs, like calling other APIs or updating lots of records, use asynchronous plugins. This keeps the system fast for users.
Tip: Keep synchronous plugins short and easy. Put big or slow jobs in asynchronous plugins so users do not have to wait.
You can make your plugins better by logging errors and testing them. Only get the data you need and do not let plugins run over and over.
Debugging Dynamics 365 Plugins
Complex Chains
When you use plugins in Dynamics 365, they can trigger each other. This can make a chain of plugins. You need to watch plugin depth and context. This helps you stop endless loops and surprises. The Plugin Registration Tool helps you debug these chains. You can use the profiler to record how plugins run. You can replay what happened and step through your code in Visual Studio. This lets you check variables and see how data moves at each stage.
You should use the ITracingService interface in your plugin code. This tool writes messages and errors while your plugin runs. You can look at these logs in the Plugin Trace Log area. Tracing shows plugin depth and context. This makes it easier to find where problems start.
Tip: Always turn on Plugin Trace Logs in system settings. This helps you see what happens when plugins run.
Troubleshooting
You have many tools and ways to find problems in the pipeline:
Use the Plugin Registration Tool to set the order and test plugins in different stages.
Profile plugins with 'Persist to Entity' or 'Exception' to save details about how they run.
Attach the Visual Studio debugger to the Plugin Registration Tool and set breakpoints in your code.
Write trace messages with ITracingService to track plugin depth and context.
Check Plugin Trace Logs for errors and to see how plugins run.
Some common problems can slow you down. You might see plugins run in the wrong order, miss handling errors, or make too many database calls. You should filter plugin steps and attributes so they only run when needed. Always use try-catch blocks and log errors before throwing them. Break your code into small methods and add clear comments. Good notes and source control help you stay organized.
Synchronous plugins need strong error handling. They can undo changes and show errors to users. Asynchronous plugins run as system jobs. You must check job logs to see if they fail. You should avoid plugins that update themselves over and over. Manage how plugins run at the same time to stop deadlocks.
You now know what each pipeline stage does in Dynamics 365. You also know why each stage is important. If you understand depth and order, you can make better customizations. This helps your work grow and makes it easier to fix problems. When you use good ways to debug and improve speed, your plugins work better. They also avoid many common problems. If you want to learn more, try these advanced courses:
FAQ
What is a plug-in in Dynamics 365?
A plug-in is custom code that you write to add new business logic to Dynamics 365. You use plug-ins to change how the system works when you create, update, or delete records.
What happens if a plug-in fails during execution?
If your plug-in fails, Dynamics 365 stops the process. The system does not save any changes. You see an error message. This helps keep your data safe.
What does plug-in depth mean?
Plug-in depth shows how many times your plug-in runs in one process. If your plug-in calls itself, the depth increases. You should check depth to avoid endless loops.
What is the difference between synchronous and asynchronous plug-ins?
Synchronous plug-ins run right away. The user waits for them to finish. Asynchronous plug-ins run in the background. The user does not wait. Use asynchronous for slow or big tasks.
What tools help you debug plug-ins?
You can use the Plugin Registration Tool, Plugin Trace Logs, and Visual Studio. These tools help you find errors, check the order of plug-ins, and see what happens during execution.