技术开发 频道

NBearV3 Step by Step教程——IoC进阶

    4.6 接着,为了让website能够访问远程Service,我们需要为website的Web.config添加serviceFactory配置节,同时为,为了演示同时存在本地Service和远程Service的情形,我们保留castle配置节中的category service。修改完的Web.config内容如下:
<?xml version="1.0"?> <configuration> <configSections> <section name="serviceFactory" type="NBear.IoC.Service.Configuration.ServiceFactoryConfigurationSection, NBear.IoC" /> <section name="entityConfig" type="NBear.Common.EntityConfigurationSection, NBear.Common"/> <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/> </configSections> <entityConfig> <includes> <add key="Sample Entity Config" value="~/EntityConfig.xml"/> </includes> </entityConfig> <castle> <components> <!--You can use standard castle component decleration schema to define service interface impls here--> <component id="category service" service="ServiceInterfaces.ICategoryService, ServiceInterfaces" type="ServiceImpls.CategoryService, ServiceImpls"/> </components> </castle> <serviceFactory type="Remoting" name="testServiceFactory" protocol="HTTP" server="127.0.0.1" port="8888" debug="true" maxTry="30" /> <appSettings/> <connectionStrings> <add name="Northwind" connectionString="Server=(local);Database=Northwind;Uid=sa;Pwd=sa" providerName="NBear.Data.SqlServer.SqlDbProvider"/> </connectionStrings> <system.web> <compilation debug="true"> <assemblies> <add assembly="System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation> <authentication mode="Windows"/> </system.web> </configuration>

     4.6 如果您想在多个服务器上测试本程序,您可以分别将ServiceMQServer和ServiceHost目录中的内容复制到不同的服务器。但是,需要注意修改所有的config中的server地址修改为ServiceMQServer所在的服务器地址。

    当然,如果只是想先看看运行效果,你也可以直接在本机运行。

    Step 5 运行分布式程序

    5.1 现在我们就可以运行整个程序了。我们首先必须先运行ServiceMQServer.exe。

    5.2 接着,我们运行两个ServiceHost.exe实例(如果您愿意,也可以运行更多)。您将能看到,在ServiceMQServer.exe的窗口中,会显示,分别由两个ICategoryService和IProductService的订阅者。他们自然是我们的ServiceHost向ServiceMQServer订阅的。

    5.3 运行website,并访问Default.aspx,你将能看到website的运行结果应该和没有部署为分布式程序之前的结果实完全一样的。您可以刷新几次页面,并注意ServiceMQServer和ServiceHost的窗口。

    您将能看到,对IProductService的请求,会被自动发送给两个ServiceHost中的一个来处理并返回,但是,你看不到ICategoryService被处理的日志。为什么呢?因为,我们在website的Web.config中的castle块中保留了本地的category service组件定义。在Default.aspx请求某个Service时,如果,ServiceFactory发现有本地实现,则会直接返回本地Service实现的实例,如果找不到本地实现,则会向ServiceMQServer发送Service调用请求,ServiceMQServer,则将把对Service的调用请求负载均衡地,转发给注册到它的ServiceHost。所以,在多刷新几次页面的时候,您将注意到,有时,请求是被一个ServiceHost处理的,有时,请求被另一个处理。

    如果你将Web.config中的category service那个component注释掉,再次刷新Default.aspx页面,则您将能看到,对category service调用,也会被发送给ServiceHost处理。

    但是,注意,此时,Category.Products总是返回null。为什么呢?因为,我们在2.3中将Category.Products属性设为只读了。只读属性是不会被序列化的,所以Products不会被传递到远程。

0
相关文章