gpt4 book ai didi

c# - 编写 CRM 2011 插件的最佳设计模式

转载 作者:太空狗 更新时间:2023-10-29 18:18:52 25 4
gpt4 key购买 nike

由于客户提供的复杂请求,有时我的代码会变得困惑。我花时间阅读和理解我上次写的东西,但这需要时间。

我想知道是否有人实现了一种好的设计模式,可以节省时间并使代码更有条理和可读性等。

最佳答案

拥有一个实现 IPlugin 的基础插件是朝着正确方向迈出的良好一步。它的 Execute 函数可以将 IServiceProvider 以及您的 dataContext 或 OrganizationService 传递到一个抽象的 onExecute 方法中,该方法被包装在一个带有虚拟错误处理程序方法的 try catch 中。这将消除大量重复的样板代码...

编辑 1

添加了显示抽象 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
}
}

编辑2

我在 DLaB.Xrm.Plugin 命名空间中的 DLaB.Xrm(在 Nuget 上)中定义了一个插件基础,它可以为您处理很多很棒的事情。 Here是一个示例插件类,向您展示如何使用它。

关于c# - 编写 CRM 2011 插件的最佳设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11097356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com