【问题标题】:Will transactionscope work over multiple calls to different services?transactionscope 是否可以处理对不同服务的多次调用?
【发布时间】:2010-06-18 10:26:37
【问题描述】:

我正在用 C# asp.NET MVC2 编写一些合并功能。我也在使用 Linq2SQL。

我有一段代码调用两个服务,MessageService 和 UserService。这些都在术语中调用其适当的存储库并对数据库进行修改。每个存储库都声明了它自己的存储库实例,因此我认为这会将以下代码升级为 DTC 。代码是从 AccountService 调用的,这会在这个级别上工作吗?在每个存储库的顶部声明 DataContext 也是不好的做法,还是我应该以某种方式传递对象?提前谢谢你

//Run the merge
try
{
    using (TransactionScope scope = new TransactionScope())
    {
        // Update Messages to be owned by primary user
        if (!_MessageService.UpdateCreatedById(MergeUser.UserID, CoreUser.UserID))
        {
            return false;
        }

        // Update Comments to be owned by primary user
        foreach (var curComment in _MessageService.GetUserComments(MergeUser.UserID))
        {
            curComment.CreatedBy = CoreUser.UserID;
        }

        _MessageService.Save();

        // Update Logins to be owned by primary user
        foreach (var CurLogin in _UserService.GetLogins(MergeUser.UserID))
        {
            CurLogin.UserID = CoreUser.UserID;
        }

        _UserService.Save();

        scope.Complete();
    }

    return true;
}
catch (Exception ex)
{
    _ErrorStack.Add(ex.Message);
    ErrorService.AddError(new ErrorModel("Portal", "WidgetRepository", ErrorHelper.ErrorTypes.Critical, ex));
    return false;
}

【问题讨论】:

    标签: asp.net datacontext transactionscope


    【解决方案1】:

    是的,这会起作用。 TransactionScope 利用分布式事务协调器,因此它能够托管超出数据库级别的事务。

    DataContext 生命周期的推荐做法是将其限制为一个工作单元。

    【讨论】:

    • 所以我不应该像 paddy 提到的那样传递服务/存储库之间的上下文?
    • TransactionScope 不知道 DataContext,也不需要知道 DataContext。 TransactionScope 甚至在 DataContext 之前就已经存在。
    【解决方案2】:

    我的存储库中有两个构造函数,一个接受数据上下文,另一个不接受(然后将其设置为自己的)。这意味着我可以根据需要使用共享数据上下文创建存储库。

    然后,我的服务类在其构造函数中采用存储库对象,因此如果需要,我可以使用共享数据上下文的存储库实例化多个服务。

    【讨论】:

    • @this。 __curious_geek - 我倾向于仅将这种技术用于跨越系统不同区域的更新(如上所述)。我调用每个服务的更新,然后在其中一个上“保存”,这将在我的数据上下文中提交更改。
    猜你喜欢
    • 2020-07-14
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多