.NET3.0: WCF Windows Communication Foundation 紹介
この文書はVisual Studio 2005 TS + Windows Vista RC2 + .NET Framework 3.0 RTMで作成されています。
.NET 3.0からWCFという新しい分散アプリケーションの作り方が増えます。
.NETの1.xから.NET リモーティンぐと、XML Web Service(.asmx)が大きな柱でしたが、従来のオリジナルプロトコルによるTCP通信やDCOMなんかも並び立っているところにもう1こ増えるというか、もう1層増えることになります。
WCFの情報が非常に少なくわかりづらいと思いますが、インストールしてサンプルを作るだけで簡単に実現可能です。
おもにWCFはSystem.ServiceModel.dllおよびSystem.ServiceModel名前空間で展開されます。
共有モジュール側のサンプルはこんな感じ。ポイントはやっぱり属性です。
[ServiceContract()]
public interface IService1
{
[OperationContract]
string MyOperation1(string myValue);
[OperationContract]
string MyOperation2(DataContract1 dataContractValue);
}
public class service1 : IService1
{
public string MyOperation1(string myValue)
{
return "Hello: " + myValue;
}
public string MyOperation2(DataContract1 dataContractValue)
{
return "Hello: " + dataContractValue.FirstName;
}
}
[DataContract]
public class DataContract1
{
string firstName;
string lastName;
[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
このクラスをホストするサービスを作る必要があります。
このあたりはリモーティングっぽいかな。
internal class MyServiceHost
{
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
//Consider putting the baseAddress in the configuration system
//and getting it here with AppSettings
Uri baseAddress = new Uri("http://localhost:8080/service1");
//Instantiate new ServiceHost
myServiceHost = new ServiceHost(typeof(WCFServiceLibrary1.service1), baseAddress);
//Open myServiceHost
myServiceHost.Open();
}
internal static void StopService()
{
//Call StopService from your shutdown logic (i.e. dispose method)
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
static void Main(string[] args)
{
MyServiceHost.StartService();
Console.ReadLine();
MyServiceHost.StopService();
}
で実際の通信規約などはApp.Configに記述します。
<configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="MyServiceTypeBehaviors" > <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="WCFServiceLibrary1.service1" behaviorConfiguration="MyServiceTypeBehaviors"> <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" /> <endpoint contract="WCFServiceLibrary1.IService1" binding="wsHttpBinding" /> </service> </services> </system.serviceModel> </configuration>
実際に重要なのはendpointっていう部分だけ。
このサービスをどの方式でというところがbindingで設定されている。
wsHttpBindingの名前でピンとくる人はピンとくると思いますが(そりゃそう)、WS-*(Web Service系規格はこんな感じで書くけど検索できないって)をサポートしていて、WS-*を簡単に使うことができるってのが目玉です。
トランザクションもできるはずです。
localhost.Service1Client s1 = new
ConsoleApplication2.localhost.Service1Client();
Console.WriteLine(s1.MyOperation1("WCF Test"));
s1.Close();
利用する側は今まで通りリモーティングやXML Web Serviceのように透過的に利用できるので難しいことは何も考えなくてもいいです。
MSONのデモでもじみーなためにあまり反応が良くなかったわけですが、WCFは確実に利用する局面の多い技術だと思われます 。(派手なWPF、導入が難しいけど私一押しのWF、手堅いWCFってとこかな?)、



