WCF でジェネリックがどのくらい利用できるのか、サンプルコードで試してみました。今回はサービスコントラクトのインタフェースをジェネリックにするケース。
まず、サービスコントラクト、データコントラクト、実際のサービスクラスを作成します。
[ServiceContract] public interface IMasterService<T> where T : class { [OperationContract] T GetData(string code); } [DataContract] public class Customer { [DataMember] public string Code { get; set; } [DataMember] public string Name { get; set; } } public class CustomerService : IMasterService<Customer> { public Customer GetData(string code) { return new Customer() { Code = code, Name = "test" }; } }
次に、ジェネリックなインタフェースを使って、サービスを呼び出せるか試すためのコードを記述。
// サービス起動 string address = "net.tcp://localhost:8000/CustomerService"; ServiceHost host = new ServiceHost(typeof(CustomerService)); host.AddServiceEndpoint( typeof(IMasterService<Customer>), new NetTcpBinding(), address); host.Open(); // サービス呼び出し IMasterService<Customer> channel = ChannelFactory<IMasterService<Customer>>.CreateChannel( new NetTcpBinding(), new EndpointAddress(address)); Customer data = channel.GetData("0001"); Console.WriteLine("{0}:{1}", data.Code, data.Name); ((IChannel)channel).Close(); Console.ReadLine(); host.Close();
ちゃんと通信できています。
インタフェース版のサービスコントラクトは、ジェネリックにできますね。「ジェネリックなインタフェースを使って、メソッドの定義を統一する」みたいな手法が、WCF でも使えそうです。