Create WCF endpoint configurations in the client app, in code?

人盡茶涼 提交于 2019-11-27 20:40:53

By default, when you do an Add Service Reference operation, the WCF runtime will generate the client-side proxy for you.

The simplest way to use it is to instantiate the client proxy with a constructor that takes no parameters, and just grab the info from the app.config:

YourServiceClient proxy = new YourServiceClient();

This requires the config file to have a <client> entry with your service contract - if not, you'll get the error you have.

But the client side proxy class generated by the WCF runtime also has additional constructors - one takes an endpoint address and a binding, for instance:

BasicHttpBinding binding = new BasicHttpBinding(SecurityMode.None);
EndpointAddress epa = new EndpointAddress("http://localhost:8282/basic");

YourServiceClient proxy = new YourServiceClient(binding, epa);

With this setup, no config file at all is needed - you're defining everything in code. Of course, you can also set just about any other properties of your binding and/or endpoint here in code.

An east way to consume a WCF service if you have a reference to the assembly which defines the interface, is using the System.ServiceModel.ChannelFactory class.

For example, if you would like to use BasicHttpBinding:

var emailService = ChannelFactory<IEmailService>.CreateChannel(new BasicHttpBinding(), new EndpointAddress(new Uri("http://some-uri-here.com/));

If you don't have a reference to the service assembly, then you can use one of the overloaded constructors on the generated proxy class to specify binding settings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!