Bagaimana untuk pemrograman menghubungkan klien ke layanan WCF?

I'm mencoba untuk menghubungkan aplikasi (klien) untuk yang terkena WCF service, tapi tidak melalui file konfigurasi aplikasi, tetapi dalam kode.

Bagaimana saya harus pergi tentang melakukan hal ini?

Mengomentari pertanyaan (1)
Larutan

Anda'll harus menggunakan ChannelFactory kelas.

Berikut ini's contoh:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Sumber daya terkait:

Komentar (6)

Anda juga dapat melakukan apa "Layanan Referensi" kode yang dihasilkan tidak

public class ServiceXClient : ClientBase, 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);
    }
}

Di mana IServiceX adalah Layanan WCF Kontrak

Kemudian klien anda kode:

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