warensoft 我是科学家

Warensoft 我是科学家

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

纯IronPython实现WCF Service

前面的Blog中简单说明了如何利用IronPython的clrtype实现.NET中的接口,有了这些功能做为前提,我们就可以使用IronPython实现WCF服务,并且调用WCF服务(并非利用C#扩展)。

实现WCF服务,对于IronPython来讲有两点是最重要的,1.如何实现.NET Interface,2.如何实现特性类(Attribute Class),实现Interface的过程,请参考前面的Blog,本次主要说明如何实现Attribute Class。

先看一个C#版本的WCF服务实现,代码如下:

[ServiceContract]

        public interface IService

        {

            [OperationContract]

            string GetAge(int age);

           

        }

        public class Service : IService

        {

            #region IService Members

 

            public string GetAge(int age)

            {

                return "hello " + age.ToString();

            }

 

            #endregion

        }

 

        static void Main(string[] args)

        {

            ServiceHost host = new ServiceHost(typeof (Service),new Uri("http://localhost/Service"));

            host .AddServiceEndpoint (typeof (IService ),new WSHttpBinding(),"");

            host.Open();

            Console.WriteLine("started");

            Console.Read();

        }

与之对应的Python代码如下所示:

# coding=gb2312

import clr

import clrtype

clr.AddReference("System.ServiceModel")

from System import Console, Uri

from System.ServiceModel import (ServiceContractAttribute,

                                 OperationContractAttribute,

                                 ServiceHost, WSHttpBinding,

                                 ServiceBehaviorAttribute,

                                 )

OperationContract = clrtype.attribute(OperationContractAttribute)

#定义接口

class IService(object):

    __metaclass__ = clrtype.ClrInterface#声明该类为接口类型

    _clrnamespace = "TestWCF"#添加命名空间

#为ISerivce接口添加ServiceContractAttribute

_clrclassattribs = [ServiceContractAttribute]

 

    @OperationContract()#用OperationContractAttribute修饰GetAge方法

    @clrtype.accepts(int)#声明参数age为int类型

    @clrtype.returns(str)#声明返回值为string类型

    def GetAge(self, age):

        raise RuntimeError("this should not get called")

#定义类

class Service(IService):

    __metaclass__ = clrtype.ClrClass

    _clrnamespace = "TestWcf"

    _clrclassattribs = [ServiceBehaviorAttribute]

 

    def GetAge(self, age):

        return "hello " + str(age)

sh = ServiceHost(clr.GetClrType(Service), Uri("http://localhost/Service"))

sh.AddServiceEndpoint(clr.GetClrType(IService), WSHttpBinding(), "")

sh.Open()

Console.WriteLine("host started")

Console.Read()

从代码量上看Python要多于C#,从运行效率上看,二都基本上是差不多的。

如果利用IronPython调用WCF,关键是要声明接口,其他的都和C#的方式是一样的,这里就不多说了。

大家如果有什么问题,请给我发Email:warensoft@foxmail.com

 

posted on 2010-03-07 15:19  王宇 warensoft  阅读(1030)  评论(0编辑  收藏  举报