Dynamics CRM: Decorator Pattern

Have you ever curious why sometimes your plugins run very slow? Then you wonder where are the critical operation that makes all of the operations slower? Of course, you can investigate this in many ways: from the database server perspective, network, etc. Today I want to share how to easily leveraging Dynamic CRM Functionality to make a simple log with a Decorator Pattern.

Decorator Pattern is a design pattern to add the functionality of a class, without changing the original behavior of that class. In this case, I will show you guys how to add new functionality in the real OrganizationService class. Without further ado, let see the example of implementation:

public class LogOrganizationService : IOrganizationService
{
	private readonly IOrganizationService _service;

	public LogOrganizationService(IOrganizationService service)
	{
		//Get the real class using Dependency Injection
		_service = service;
	}

	public Guid Create(Entity entity)
	{
		var now = DateTime.Now;
		var result = _service.Create(entity);
		var end = DateTime.Now;

		return result;
	}
}

The LogOrganizationService constructor retrieves the real implementation of IOrganizationService. Then the LogOrganizationService class works as a wrapper of that class. For example, we wrap the Create operation to do logger.

Then for using this one, we only to do like this:

public class PostIncidentCreate : IPlugin
{
	public void Execute(IServiceProvider serviceProvider)
	{
		var service = (IOrganizationService)serviceProvider.GetService(typeof(IOrganizationService));
		var decorateService = new LogOrganizationService(service);

		//Do your business logic using decorateService
	}
}

Viola, you already learn about decorator pattern!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.