Compartilhar via


Transmitir dados entre os plug-ins

 

Publicado: janeiro de 2017

Aplicável a: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

O modelo de pipeline de mensagens para Microsoft Dynamics 365 define uma coleta de parâmetros de valores de dados personalizados no contexto de execução que são passados através do pipeline e compartilhados entre os plug-ins registrados, independentemente dos diferentes desenvolvedores de terceiros. Este conjunto de dados pode ser usado por diferentes plug-ins para comunicar informações entre plug-ins e habilitar o processamento de cadeia em que os dados processados por um plug-in possam ser processados pelo seguinte plug-in na sequência e assim por diante. Esse recurso é muito útil nos cenários de mecanismo de precificação onde vários plug-ins de precificação transmitem dados entre si para calcularem o preço total de uma ordem de venda ou fatura. Outro uso potencial para esse recurso é comunicar informações entre um plug-in registrado de um pré-evento e um plug-in registrado de um pós-evento.

O nome do parâmetro que é usado para transmitir informações entre os plug-ins é SharedVariables. Trata-se de um conjunto de pares de valores\chaves. Durante o tempo de execução, os plug-ins podem adicionar, ler ou alterar propriedades na coleta SharedVariables. Isso fornece um método de comunicação de informações entre os plug-ins.

Este exemplo mostra como usar SharedVariables para passar dados de um plug-in registrado pré-evento a um plug-in registrado pós-evento.


using System;

// Microsoft Dynamics CRM namespace(s)
using Microsoft.Xrm.Sdk;

namespace Microsoft.Crm.Sdk.Samples
{
    /// <summary>
    /// A plug-in that sends data to another plug-in through the SharedVariables
    /// property of IPluginExecutionContext.
    /// </summary>
    /// <remarks>Register the PreEventPlugin for a pre-operation stage and the 
    /// PostEventPlugin plug-in on a post-operation stage.
    /// </remarks>
    public class PreEventPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            // Create or retrieve some data that will be needed by the post event
            // plug-in. You could run a query, create an entity, or perform a calculation.
            //In this sample, the data to be passed to the post plug-in is
            // represented by a GUID.
            Guid contact = new Guid("{74882D5C-381A-4863-A5B9-B8604615C2D0}");

            // Pass the data to the post event plug-in in an execution context shared
            // variable named PrimaryContact.
            context.SharedVariables.Add("PrimaryContact", (Object)contact.ToString());
        }
    }

    public class PostEventPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            // Obtain the contact from the execution context shared variables.
            if (context.SharedVariables.Contains("PrimaryContact"))
            {
                Guid contact =
                    new Guid((string)context.SharedVariables["PrimaryContact"]);

                // Do something with the contact.
            }
        }
    }
}


' Microsoft Dynamics CRM namespace(s)
Imports Microsoft.Xrm.Sdk

Namespace Microsoft.Crm.Sdk.Samples

    ''' <summary>
    ''' A plug-in that sends data to another plug-in through the SharedVariables
    ''' property of IPluginExecutionContext.
    ''' </summary>
    ''' <remarks>Register the PreEventPlugin for a pre-operation stage and the 
    ''' PostEventPlugin plug-in on a post-operation stage.
    ''' </remarks>
    Public Class PreEventPlugin
        Implements IPlugin

        Public Sub Execute(ByVal serviceProvider As IServiceProvider) _
            Implements IPlugin.Execute

            ' Obtain the execution context from the service provider.
            Dim context As Microsoft.Xrm.Sdk.IPluginExecutionContext =
                CType(serviceProvider.GetService(
                        GetType(Microsoft.Xrm.Sdk.IPluginExecutionContext)), 
                    Microsoft.Xrm.Sdk.IPluginExecutionContext)

            ' Create or retrieve some data that will be needed by the post event
            ' plug-in. You could run a query, create an entity, or perform a calculation.
            'In this sample, the data to be passed to the post plug-in is
            ' represented by a GUID.
            Dim contact As New Guid("{74882D5C-381A-4863-A5B9-B8604615C2D0}")

            ' Pass the data to the post event plug-in in an execution context shared
            ' variable named PrimaryContact.
            context.SharedVariables.Add("PrimaryContact", CType(contact.ToString(),
                                        Object))

        End Sub
    End Class

    Public Class PostEventPlugin
        Implements IPlugin

        Public Sub Execute(ByVal serviceProvider As IServiceProvider) _
            Implements IPlugin.Execute

            ' Obtain the execution context from the service provider.
            Dim context As Microsoft.Xrm.Sdk.IPluginExecutionContext =
                CType(serviceProvider.GetService(
                        GetType(Microsoft.Xrm.Sdk.IPluginExecutionContext)), 
                    Microsoft.Xrm.Sdk.IPluginExecutionContext)

            ' Obtain the contact from the execution context shared variables.
            If context.SharedVariables.Contains("PrimaryContact") Then

                Dim contact As New Guid(CStr(context.SharedVariables("PrimaryContact")))

                ' Do something with the contact.

            End If

        End Sub
    End Class

End Namespace

É importante que qualquer tipo de dado adicionado ao conjunto de variáveis ​​compartilhadas seja serializável, caso contrário o servidor não saberá como serializar os dados e a execução do plug-in falhará.

Para um plug-in registrado no estágio 20 ou 40, para acessar as variáveis compartilhadas de um plug-in registrado em estágio 10 que executa em criar, atualizar, excluir ou por um RetrieveExchangeRateRequest, é necessário acessar o conjunto ParentContext.SharedVariables. Para todos os outros casos, IPluginExecutionContext.SharedVariables contém um conjunto.

Confira Também

IPluginExecutionContext
Desenvolvimento de plug-in
Representação em plug-ins
Pipeline de execução do evento

Microsoft Dynamics 365

© 2017 Microsoft. Todos os direitos reservados. Direitos autorais