Jak programowo podłączyć klienta do usługi WCF?

Próbuję połączyć aplikację (klienta)z odsłoniętą usługą WCF, ale nie poprzez plik konfiguracyjny aplikacji, ale w kodzie.

Jak mam to zrobić?

Author: Luke Girvin, 2010-05-31

2 answers

Będziesz musiał użyć klasy ChannelFactory .

Oto przykład:

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();
    }
}

Powiązane zasoby:

 103
Author: Enrico Campidoglio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-25 10:00:46

Możesz również zrobić to, co robi wygenerowany kod "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);
    }
}

Gdzie IServiceX jest Twoją umową serwisową WCF

Następnie Twój kod klienta:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
 6
Author: joseph.l.hunsaker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-20 00:26:43