当前位置: 代码迷 >> Web Service >> wcf 不会rollback,请大家伙儿帮忙看看
  详细解决方案

wcf 不会rollback,请大家伙儿帮忙看看

热度:148   发布时间:2016-05-02 02:26:16.0
wcf 不会rollback,请大家帮忙看看。
在学习wcf,最近学到wcf事务。自己写了一个示例,就是不会rollback,请大家帮忙看看。
服务器端代码:
namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(Calc));

            WSHttpBinding wsbinding = new WSHttpBinding();

            wsbinding.TransactionFlow = true;
            host.AddServiceEndpoint(typeof(ICalc), wsbinding, "http://localhost:8003");

            host.Opened += delegate
            {
                Console.WriteLine("services is open!");
            };

            host.Open();
            Console.ReadKey();
        }
    }

    [ServiceContract]
    public interface ICalc
    {
        [OperationContract]
        [TransactionFlow(TransactionFlowOption.Mandatory)]
        double Add(double x);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class Calc : ICalc
    {
        [OperationBehavior(TransactionScopeRequired = true)]
        public double Add(double x)
        {
            Console.WriteLine(Transaction.Current.TransactionInformation.CreationTime);
            Console.WriteLine(Transaction.Current.TransactionInformation.LocalIdentifier);
            return x + 1;
        }
    }
}

然后客户端代码:
    class Program
    {
        static void Main(string[] args)
        {
            WSHttpBinding ws = new WSHttpBinding();
            ws.TransactionFlow=true;

            ChannelFactory<ICalc> mychannel = new ChannelFactory<ICalc>(ws, "http://localhost:8003");
            mychannel.Open();

            ICalc myclient = mychannel.CreateChannel();

            double x = 3.5;
            double y = 0;
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
            {                
                try
                {
                    Console.WriteLine(Transaction.Current.TransactionInformation.CreationTime);
                    Console.WriteLine(Transaction.Current.TransactionInformation.LocalIdentifier);
                    y = myclient.Add(x);
                    throw new Exception("throw new exception");
                    scope.Complete();
                    mychannel.Close();
                }
                catch (Exception ex)
  相关解决方案