Dynamics CRM: Decorator Pattern
Have you ever been curious why sometimes your plugins run very slow? Then you wonder where are the critical operations that make all of the operations slower? Of course, you can investigate this in many ways: from a database server perspective, network, etc. Today I want to share how to easily leverage Dynamic CRM Functionality to make a simple log with a Decorator Pattern.
Decorator Pattern is a design pattern to add a 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 a real OrganizationService class. Without further ado, let's 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 just works as a wrapper of that class. For example in these, we wrap the Create operation to do logger.
Then to use this one, we only have to do 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 learned your decorator pattern!
Leave a comment
Your comment is sent privately to the author and isn't published on the site.