Plantilla de plugin en Dataverse: contexto, servicio y Target
Todos los plugins arrancan igual. Hay que sacar el contexto, el servicio de trazas, el servicio de organización y el registro que ha disparado el plugin (Target). Esta es la base que copio siempre:
public void Execute(IServiceProvider serviceProvider)
{
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = factory.CreateOrganizationService(context.UserId);
if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity target))
return;
tracing.Trace("Plugin ejecutado sobre {0} {1}", target.LogicalName, target.Id);
// Tu lógica aquí
}Con CreateOrganizationService(context.UserId) el servicio usa los permisos del usuario que lanzó la acción. Si le pasas null se ejecuta como SYSTEM y se salta la seguridad, algo que yo solo hago cuando no queda otra.
La comprobación del tipo del Target tampoco está de adorno. En un Delete llega una EntityReference y no una Entity, así que si haces el cast directamente a Entity, el plugin falla.
Por último, en un Update el Target solo trae los campos que han cambiado. Si necesitas leer alguno más, configura una pre-image en el paso.