CRM 2011 Plugins – IServiceProvider

Roshan Mehta, 03 April 2013

When a particular event occurs in Microsoft Dynamics CRM, such as “create of a contact” or “update of an account”, the Execute method is invoked for any plugins registered on the event. This method includes a single serviceProvider parameter which provides useful service information about the execution of the plugin. In this post, we will take a look at the information that is made available by the serviceProvider parameter.

 CRM 2011 Plugins IServiceProvider

The types of service objects available include the following:

• IPluginExecutionContext
• IOrganizationServiceFactory
• ITracingService

The IPluginExecutionContext service object is the most useful of the three and provides contextual information to the plugin at run-time. It includes details about the user who triggered the plugin event as well as transactional information handled at the platform layer. The following code can be used to obtain the execution context from the service provider:

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

The IOrganizationServiceFactory service object allows us to create an instance of the organization service which can be used to define and execute various platform requests. The following code can be used to achieve this:

IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService sdk = factory.CreateOrganizationService(context.UserId);  

In the example above, we pass in the GUID of the user who triggered the plugin event, which is obtained from the IPluginExecutionContext. Alternatively, we can pass in the GUID of another CRM user, or pass in a null value to execute the plugin logic under the system context.

Lastly, the ITracingService allows us to trace the plugin execution flow and any variables for debugging purposes. For more information, please read my post on Debugging Dynamics CRM 2011 Plugins.

There you have it, an introduction to the various service objects that we will be working with in our journey to create plugins for Microsoft Dynamics CRM. In my next post, we will take a closer look at the IPluginExecutionContext.

Image from http://i.telegraph.co.uk/multimedia/archive/02365/coding_alamy_2365972b.jpg