Anw*_*war 8 c# dynamics-crm-2011
由于客户提供的复杂请求,有时我的代码会变得混乱.自上次我在插件上工作以来,我花时间阅读并理解我之前写过的内容.
我想知道是否有人实现了一个好的设计模式,节省了大量的时间,使代码更有组织和可读性等.
拥有一个实现IPlugin的基本插件是朝着正确方向迈出的一大步.它的Execute函数可以将IServiceProvider以及dataContext或OrganizationService传递给抽象的onExecute方法,该方法包含在带有虚拟错误处理程序方法的try catch中.这将消除大量重复的样板代码......
添加了显示抽象OnExecute和虚拟错误处理程序的代码示例:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我在DLaB.Xrm.Plugin命名空间中的DLaB.Xrm(在Nuget上)定义了一个插件库,它允许为您处理很多很棒的事情. 这是一个示例插件类,向您展示如何使用它.