gpt4 book ai didi

c# - 带有 prolog 和 epilog 的设计模式

转载 作者:行者123 更新时间:2023-12-02 05:40:39 24 4
gpt4 key购买 nike

我正在寻找可以实现一些序言代码和结尾代码的设计模式。让我解释一下:

我有一个函数(其中有很多)几乎做同样的事情:

这是伪代码,但实际上它是用 C# 4.5 编写的

public IDatabaseError GetUserByName(string Name)
{
try
{
//Initialize session to database
}
catch (Exception)
{
// return error with description for this step
}

try
{
// Try to create 'transaction' object
}
catch(Exception)
{
// return error with description about this step
}

try
{
// Execute call to database with session and transaction object
//
// Actually in all function only this section of the code is different
//
}
catch(Exception)
{
// Transaction object rollback
// Return error with description for this step
}
finally
{
// Close session to database
}

return everything-is-ok
}

因此 - 如您所见,“prolog”(创建 session 、事务、其他辅助函数)和“epilog”(关闭 session 、回滚事务、清理内存等)对于所有 功能。

一些限制:

  • 我想将 session 和事务对象的创建/销毁过程保持在函数中,而不是在 ctor 中

  • 自定义代码(在中间运行的代码)必须包裹在 try/catch 中,并针对不同的情况返回不同的错误

  • 我愿意接受任何 Func<>、Action<> 更可取的 Task<> 函数建议

    对设计模式或代码重构有什么想法吗?

最佳答案

这可以通过使用 IDisposable 对象来实现,例如:

using(var uow = new UnitOfWork() )
using(var t = new TransactionScope() )
{
//query the database and throws exceptions
// in case of errors
}

请不要TransactionScope class 是您在 System.Transaction 中拥有的开箱即用的类,它可以(不仅)与数据库连接一起工作。在 UnitOfWork constructor 中执行“Prologue”代码(即打开连接...),在 Dispose 中执行结尾部分。通过在发生错误时抛出异常,您可以确定结尾部分无论如何都会被调用。

关于c# - 带有 prolog 和 epilog 的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11011275/

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