在之前的博客中,我记录过如何利用SvcUtil.exe工具生成客户端的代理文件,然后调用的情形。
今天我要讲解的是利用代码直接对服务端进行调用。好处在于,一是不会生成那么大的引用文件,其次是可以方便控制。首先感谢本文:分享基于EF+WCF的通用三层架构及解析提供的源代码。
首先服务器端的我就不用写了,这里我贴出OperationContract的内容:
1: public Book GetBook(int bookID)
2: {
3: return new Book
4: {
5: BookID = 1,
6: BookAuthor = "石朝阳",
7: BookName = "企业架构模式",
8: BookPrice = 85.2M,
9: BookPublishment = "清华大学出版社"
10: };
11: }
服务器端的代码没什么特别的。
下面是客户端的调用代码:
首先,声明一个IServiceFactory接口,这个接口中有CreateService方法:
1: public interface IServiceFactory
2: {
3: IBookService CreateService();
4: }
然后声明一个RemoteServiceFactory类,这个类中提供创建客户端引用的实例:
1: public class RemoteServiceFactory:IServiceFactory
2: {
3: private readonly string serviceUri = "http://localhost:12665/BookService.svc";
4:
5: public IBookService CreateService()
6: {
7: return this.CreateService<IBookService>(serviceUri);
8: }
9:
10: private const int maxReceivedMessageSize = 2147483647;
11:
12: private T CreateService<T>(string uri)
13: {
14: var key = string.Format("{0} - {1}",typeof(T),uri);
15: var binding = new BasicHttpBinding();
16: binding.MaxReceivedMessageSize = maxReceivedMessageSize;
17: binding.ReaderQuotas = new XmlDictionaryReaderQuotas();
18: binding.ReaderQuotas.MaxStringContentLength = maxReceivedMessageSize;
19: binding.ReaderQuotas.MaxArrayLength = maxReceivedMessageSize;
20: binding.ReaderQuotas.MaxBytesPerRead = maxReceivedMessageSize;
21:
22: ChannelFactory<T> chan = new ChannelFactory<T>(binding,new EndpointAddress(uri));
23: foreach (var operation in chan.Endpoint.Contract.Operations)
24: {
25: var dataContractBehavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>()
26: as DataContractSerializerOperationBehavior;
27: if (dataContractBehavior != null)
28: dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
29: }
30: chan.Open();
31:
32: var service = chan.CreateChannel();
33: return service;
34: }
35: }
最后在程序中调用即可:
1:
2: static void Main(string[] args)
3: {
4: Program program = new Program();
5: Book book = program.Service.GetBook(2);
6: Console.WriteLine("Book ID:"+book.BookID.ToString());
7: Console.WriteLine("Book Name:" + book.BookName.ToString());
8: Console.WriteLine("Book Author:" + book.BookAuthor.ToString());
9: Console.WriteLine("Book Publishment:" + book.BookPublishment.ToString());
10: Console.WriteLine("Book Price:" + book.BookPrice.ToString());
11:
12: Console.ReadKey();
13: }
14:
15: public IServiceFactory ServiceFactory
16: {
17: get
18: {
19: //Need to inject dynamic later
20: return new RemoteServiceFactory();
21: }
22: }
23:
24: public IBookService Service
25: {
26: get
27: {
28: return this.ServiceFactory.CreateService();
29: }
30: }
得到的结果如下: