ProgramingTip

프로그래밍 방식으로 클라이언트를 WCF 서비스에 연결하는 방법은 무엇입니까?

bestdevel 2020. 10. 24. 11:22
반응형

프로그래밍 방식으로 클라이언트를 WCF 서비스에 연결하는 방법은 무엇입니까?


애플리케이션 (클라이언트)을 노출 된 WCF 서비스에 연결하려고 애플리케이션 구성 파일을 통하지 않고 코드로 연결합니다.

이 작업을 어떻게해야합니까?


ChannelFactory 클래스 를 사용합니다 .

예를 들면 다음과 같습니다.

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

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

관련 자료 :


"서비스 참조"생성 코드가 수행하는 작업을 수행 할 수도 있습니다.

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");

참고 URL : https://stackoverflow.com/questions/2943148/how-to-programmatically-connect-a-client-to-a-wcf-service

반응형