Подтвердить что ты не робот

Как программно подключить клиента к службе WCF?

Я пытаюсь подключить приложение (клиент) к открытой службе WCF, но не через файл конфигурации приложения, а в код.

Как мне это сделать?

4b9b3361

Ответ 1

Вам нужно будет использовать класс ChannelFactory.

Вот пример:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint);

IMyService client = null;

try
{
    client = myChannelFactory.CreateChannel();
    client.MyServiceOperation();
    ((ICommunicationObject)client).Close();
}
catch
{
    if (client != null)
    {
        ((ICommunicationObject)client).Abort();
    }
}

Связанные ресурсы:

Ответ 2

Вы также можете сделать то, что сгенерировал код "Service Reference"

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Где IServiceX - ваш Сервисный контракт WCF

Затем ваш код клиента:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");