WCF入門-06。サービス参照の追加でWSDLからクライアントのアプリケーション構成ファイルとカスタムクラスを作成する。
WSDLをサービス参照の設定で取り込むサンプルコードWCFService-06.zip
WCFのサーバーをアプリケーション構成ファイルで構成する方法と、公開するサービスをWSDLで公開する方法を見てきました。今回は公開されたWSDLから、クライアントがサーバに接続するためのアプリケーション構成ファイルとカスタムクラスを作成します。
WCFサーバを起動した状態で、VisualStudioのソリューションエクスプローラの右クリックメニューから[サービス参照の追加]を選択すると以下の画面が表示されます。
アドレスにWSDLのURLを入力して移動を押すとWSDLを取得できます。名前空間を決めてOKを押すとapp.config(アプリケーション構成ファイル)とService Reference(カスタムクラス)が生成されます。今までWCFインタフェースを参照設定して作成してきましたが、今回はWSDLを参照設定して自動生成されたカスタムクラスを使用してサーバへアクセスする方式になります。
WCFインタフェースを参照設定する方式と比べてみると違いが良く分かります。
- WCFインタフェースを参照設定してアクセスする方法の場合
Imports System.ServiceModel
Imports WCFInterfacePublic Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim endPoint As EndpointAddress = Nothing
endPoint = New EndpointAddress("http://localhost:8000/WCFService/HelloWCF")Dim httpBind As System.ServiceModel.BasicHttpBinding = Nothing
httpBind = New System.ServiceModel.BasicHttpBinding()Dim proxy As WCFInterface.ISampleService = Nothing
proxy = ChannelFactory(Of WCFInterface.ISampleService).CreateChannel(httpBind, endPoint)Dim param As New WCFInterface.BasicParameter
Dim result As WCFInterface.BasicResult = Nothingparam.Type = TypeEnum.Text
param.Message = "Hello WCF TextMessage"result = proxy.HelloWCF(param)
MsgBox(result.Result.ToString + vbCrLf + result.Message)
param.Type = TypeEnum.XML
param.Message = "- Hello WCF XMLMessage
"result = proxy.HelloWCF(param)
MsgBox(result.Result.ToString + vbCrLf + result.Message)
End Sub
End Class
- 自動生成されたカスタムクラスでサーバにアクセスするコードは以下のようになります。
Imports System.ServiceModel
Imports WCFClient.ServiceReference1Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim client As New ServiceReference1.SampleServiceClient
Dim param As New WCFClient.ServiceReference1.BasicParameter
Dim result As WCFClient.ServiceReference1.BasicResult = Nothingparam.Type = TypeEnum.Text
param.Message = "Hello WCF TextMessage"result = client.HelloWCF(param)
MsgBox(result.Result.ToString + vbCrLf + result.Message)
param.Type = TypeEnum.XML
param.Message = "- Hello WCF XMLMessage
"result = client.HelloWCF(param)
MsgBox(result.Result.ToString + vbCrLf + result.Message)
End Sub
End Class