【问题标题】:Change connectionstring based on TransactionScope in WCF project (baseHttpBinding)在 WCF 项目 (baseHttpBinding) 中根据 TransactionScope 更改连接字符串
【发布时间】:2013-10-02 09:17:21
【问题描述】:

在整个应用程序中使用静态类tConfig.ConnectionString 下载必要的连接字符串。不幸的是,我需要能够根据引用是否指向TransactionScope 来修改连接。目前,我有这段代码,但静态类称我为 StackOverflow 错误。请帮助实现此类静态(或更好的解决方案)中的功能。

public static class tConfig
{   
    public static string ConnectionString
    {
        get {
            if (System.Transactions.Transaction.Current != null)
                return "ConnectionString with scope";
            else
                return "ConnectionString without scope";
        }
    }
}

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string GetData;

    [OperationContract]
    string GetDataWithScope;
}


public class MyService : IMyService
{
    public string GetData
    {
        using (var context = new MyEntities(tConfig.ConnectionString)
        {
            return context.table1.where(x=>x.ID == 1).Select(x=> x.F_NAME).FirstOrDefault().ToString();
        }
    }

    public string GetDataWithScope
    {
        using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(600)))
        {
            using (var context = new MyEntities(tConfig.ConnectionString)
            {
                return context.table1.where(x=>x.ID == 1).Select(x=> x.F_NAME).FirstOrDefault().ToString();
            }
        }
    }
}

【问题讨论】:

  • 为什么要用transactionScope进行select操作?
  • 这只是一个例子。我将它用于 AddObject 并更新

标签: c# wcf connection-string transactionscope


【解决方案1】:

我认为以这种方式使用事务处理是个坏主意。交易何时完成?在您的代码中没有 Complete 或 RollBack 调用。由于每次调用的线程不同,每次调用的作用域会有所不同。

this link。它描述了在 wcf 级别使用事务的方法。 在这种情况下,客户端可以创建并完成事务范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    相关资源
    最近更新 更多