簡單介紹一下通過Spring.Net的IoC容器開發WCF 服務。
示例使用的Spring.Net 版本:1.3.2。本節介紹的是基於Spring.Net的IoC容器來開發WCF服
務。這種方式和之前WCF開發差別不大,只是服務的寄宿、以及客戶端代理的創建都交由
Spring.Net來完成。以下通過一個簡單示例進行說明。
publicinterface IAdd
{
[OperationContract]
int Add(int x, int y);
}
<!--提供服務的類-->
<object id="addSerivce" type="ServiceHost.AddService,ServiceHost" singleton="false"></object>
<object id="serviceFactory" type="Spring.ServiceModel.Activation.ServiceHostFactoryObject,Spring.Services">
<property name="TargetName" value="addSerivce"></property>
</object>
</objects>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="addSerivce" behaviorConfiguration="DefaultBehavior">
<host>
<baseAddresses>
<add baseAddress="http://127.0.0.1:6633/"/>
</baseAddresses>
</host>
<endpoint address="AddService" binding="basicHttpBinding" contract="Contracts.IAdd"></endpoint>
</service>
</services>
</system.serviceModel>
為了寄宿服務,定義了一個繼承自IFactoryObject的Spring.ServiceModel.Activation.
ServiceHostFactoryObject對象,並將它的TargetName屬性指定為服務實現類(由於服務實現過於簡單,就沒有給出服務的實現。服務的類名為:AddService,處 於ServiceHost程序集下)。
之前name指定為類的全局限定名,即:程序集+類型名;使用Spring.Net的IoC后只需要將name設置為服務類型的定義的Id或者nane屬性。
SpringServiceHost實例來寄宿服務;而SpringServiceHost也通過Spring.Net進行配置。
2、服務寄宿:
Console.WriteLine("Service is running...");
Console.Read();
3、客戶端配置:
xmlns:wcf= " http://www.springframework.net/wcf ">
<wcf:channelFactory channelType= " Contracts.IAdd,Contracts "
endpointConfigurationName= " addService " id= " addService ">
</wcf:channelFactory>
</objects>
<spring>
<context>
<resource uri= " assembly://Client/Client.Config/WCFServiceConfig.xml "></resource>
</context>
</spring>
<system.serviceModel>
<client>
<endpoint address= " http://127.0.0.1:6633/AddService "
binding= " basicHttpBinding "
contract= " Contracts.IAdd " name= " addService "></endpoint>
</client>
</system.serviceModel>
本例中,將此配置放在單獨的配置文件WCFServiceConfig.xml中,在 App.Config文件中對他的引用進行申明。
提示:
獲取服務代理對象並調用服務:
{
Console.WriteLine(string.Format("invocation result is :{0}", proxy.Add(1, 2)));
(proxy as ICommunicationObject).Close();
}
Console.WriteLine(string.Format("invocation result is :{0}", proxy0.Add(5, 2)));
(proxy0 as ICommunicationObject).Close();

客戶端端:
