问题描述
我需要我的服务来消费其他服务,我需要在代码中配置这些依赖.我该怎么做呢?
I need my service to consume other services, and I need to configure these dependencies in code. How do I do this?
通过以下(示例)在配置中非常简单:
This is very simple in config via the following (example):
<client>
<endpoint name="registerService"
address="http://127.0.0.1/registration/" binding="basicHttpBinding"
contract="*"/>
</client>
但出于某种原因,找到等效的代码并不像我想象的那么容易.
But for some reason finding the code equivalent is not as easy as I thought it'd be.
推荐答案
如果您使用的是 Visual Studio 生成的代理(通过添加服务引用..."),那么您使用的是 ClientBase
抽象类 &您将拥有许多构造函数,允许您传入配置部分、端点、绑定等.
If you're using the Visual Studio generated proxy (via "Add Service Reference..."), then you're using the ClientBase
abstract class & you'll have a number of constructors that allow you to pass in a config section, an endpoint, a binding etc.
http://msdn.microsoft.com/en-us/library/ms576141.aspx
如果您要实例化 ChannelFactory,那么您又需要使用许多构造函数.
And if you're instantiating a ChannelFactory then you again have a number of constructors to use.
http://msdn.microsoft.com/en-us/library/ms576132.aspx
// create bindings & endpoints
var binding = new System.ServiceModel.BasicHttpBinding();
var endpoint = new EndpointAddress("http://localhost/MyService.svc");
var factory = new ChannelFactory<IMyService>(binding, endpoint);
var channel = factory.CreateChannel();
// then call your operations...
channel.MyOperation();
这篇关于如何以编程方式添加 WCF 客户端端点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!