Due to complex requests provided by customers, sometimes my code get's messy. I take time to read and understand what I've written since I last worked on it but it takes time.
I was wondering if anyone has implemented a good design pattern which saves time and makes code more organized and readable etc.
Having a base plugin that implements IPlugin is a good step in the right direction. It's Execute function could pass in the IServiceProvider as well as your dataContext or OrganizationService into an abstract onExecute method, which is wrapped in a try catch with a virtual error handler method. This would eliminate a lot of repetitive boilerplate code...
Added code example showing an abstract OnExecute and a virtual error handler:
public abstract class PluginBase : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
try
{
OnExecute(serviceProvider);
}
catch (Exception ex)
{
bool rethrow = false;
try
{
OnError(ex);
}
catch
{
rethrow = true;
}
if (rethrow)
{
throw;
}
}
finally
{
OnCleanup();
}
}
// method is marked as abstract, all inheriting class must implement it
protected abstract void OnExecute(IServiceProvider serviceProvider);
// method is virtual so if an inheriting class wishes to do something different, they can
protected virtual void OnError(Exception ex){
// Perform logging how ever you log:
Logger.Write(ex);
}
/// <summary>
/// Cleanup resources.
/// </summary>
protected virtual void OnCleanup()
{
// Allows inheriting class to perform any cleaup after the plugin has executed and any exceptions have been handled
}
}
I have a plugin base defined in DLaB.Xrm (on Nuget) in the DLaB.Xrm.Plugin Namespace that allows handles a lot of great things for you. Here is an example plugin class showing you how to use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With