実は今まで仕事でWCFを使ったことがない。
機能追加とかが多いので、相変わらずASMXを使っている。
で、簡単なサンプルを書いてみる。
今回の方針は「実装量を極力減らし、定義で対応する」こと。
まずは、サービスの実装は、こんな感じ。プロジェクトタイプはライブラリ。
namespace LightHearted
{
[ServiceContract(Namespace = "http://hoge.light-hearted.net")]
public interface IHoge
{
[OperationContract]
string DoSomething(string param1);
}
public class Hoge : IHoge
{
public string DoSomething(string param1)
{
Console.WriteLine("DoSomething called");
return "DoSomething : " + param1;
}
}
}
そしてこれをホストするアプリ(コンソール)はこんな感じ。
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(LightHearted.Hoge)))
{
Console.WriteLine("service starting...");
host.Open();
Console.WriteLine("to stop service, press enter key");
Console.ReadLine();
host.Close();
}
}
個人的には、typeof(LightHearted.Hoge)の部分も、
App.configで定義できればさらに抽象度が上がると思うのだが、
コンパイル時チェックができなくなるからなぁ
そして、そのApp.configはこんな感じ。
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="behavior1">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="behavior1" name="LightHearted.Hoge">
<endpoint address="Hoge" binding="basicHttpBinding" name="basicHttp" contract="LightHearted.IHoge"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8888/LightHearted"/>
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
MEXを公開するような場合は、behaviorsの定義とかが必要になるみたい。
そしてクライアントからはサービスの参照設定(http://localhost:8888/Lighthearted?wsdl)をすると、
App.configにごちゃごちゃと追加される。そしてそれを使ったサービス呼び出しのコードはこんな感じ。
private void button1_Click(object sender, EventArgs e)
{
HogeClient client = new HogeClient();
try
{
string s1 = client.DoSomething("Hello WCF");
MessageBox.Show(s1);
}
catch (CommunicationException ex)
{
MessageBox.Show("CommunicationException:" + ex.Message);
}
client.Close();
}
とこんな感じになる。
開発は最初のライブラリの実装がほとんどになるのだろう。
2つ目のホストはIISを使うことになるのだろう。
クライアントは「よろしく!」ってことで。。。