Microsoft MVP성태의 닷넷 이야기
.NET Framework: 106. WCF - 다중 서비스 호스트 [링크 복사], [링크+제목 복사],
조회: 17127
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일


WCF - 다중 서비스 호스트


가끔, 이에 대해서 물어보는 경우가 있어서 차후 반복되는 답변을 위해서 미리 써볼까 합니다. (사실, 그다지 기술적인 팁은 아니지만.)

먼저, 대강 WCF 서비스를 만드는 방법을 훑어 볼까요!

WCF 서비스를 위해서는 대체로 2개의 클래스/인터페이스가 필요합니다. 먼저, 아래와 같이 ServiceContract를 만들고,

[ServiceContract]
public interface IServiceA
{
    [OperationContract]
    string GetServiceName();
}

그다음, 당연히 이에 대한 구현 클래스를 만들어야죠.

[ServiceBehavior]
public class ServiceAImp : IServiceA
{
    public string GetServiceName()
    {
        return "ServiceA";
    }
}

이렇게 마련되면, 다음과 같이 서비스 호스팅을 하게 되지요.

public partial class Form1 : Form
{
    ServiceHost aHost;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        aHost = new ServiceHost(typeof(ServiceAImp));
        aHost.Open();
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        aHost.Close();
    }
}




일단, 서비스 하나는 위와 같이 정의를 해서 호스팅을 하는 상태에서, 별도로 다른 서비스를 정의하려면 역시나 다음과 같이 ServiceContract 클래스와 ServiceBehavior 클래스를 추가해 주는 것으로 시작할 수 있습니다.

[ServiceContract]
public interface IServiceB
{
    [OperationContract]
    string GetServiceName();
}

[ServiceBehavior]
public class ServiceBImp : IServiceB
{
    public string GetServiceName()
    {
        return "ServiceB";
    }
}

질문을 하시는 분들 중에 대부분이 위와 같은 정도로 정의를 해놓고 더 이상 어찌할 바를 모릅니다. 그렇죠! 방법은 의외로 간단합니다. 별도의 ServiceHost를 하나 더 정의해서 추가해 주면 되는 것입니다.

public partial class Form1 : Form
{
    ServiceHost aHost;
    ServiceHost bHost;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        aHost = new ServiceHost(typeof(ServiceAImp));
        aHost.Open();
        bHost = new ServiceHost(typeof(ServiceBImp));
        bHost.Open();
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        aHost.Close();
        bHost.Close();
    }
}

간단하지요. ^^

물론, app.config에 추가되는 서비스 관련 환경 설정도 ServiceA에서 해주는 것과 동일하게 ServiceB도 추가해 주면 됩니다. 물론, 서비스끼리 포트를 공유해서 설정하는 것도 가능합니다.

<system.serviceModel>
    <services>
        <!-- Service A -->
        <service behaviorConfiguration="ServiceAHost.ServiceBehavior"
                name="ServiceHostWinApp.ServiceAImp">
            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:24000/ServiceA" />
                    <add baseAddress="net.tcp://localhost:24001/" />
                </baseAddresses>
            </host>
            <endpoint address="ServiceA" binding="netTcpBinding" bindingConfiguration="ServiceA_TcpBinding"
                      contract="ServiceHostWinApp.IServiceA" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        </service>

        <!-- Service B -->
        <service behaviorConfiguration="ServiceBHost.ServiceBehavior"
                name="ServiceHostWinApp.ServiceBImp">
            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:24000/ServiceB" />
                    <add baseAddress="net.tcp://localhost:24001/" />
                </baseAddresses>
            </host>
            <endpoint address="ServiceB" binding="netTcpBinding" bindingConfiguration="ServiceB_TcpBinding"
                      contract="ServiceHostWinApp.IServiceB" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        </service>
    </services>
    
    .... [중간 생략] ....
</system.serviceModel>

baseAddress 설정에서 http 부분에 대해서는 별도로 "ServiceA", "ServiceB"를 붙였는데요. 왜냐하면, mex 기능이 해당 baseAddress를 기준으로 그대로 "mex"만을 붙여서 endpoint를 정하기 때문입니다. 그래서 2개의 endpoint가 "http://localhost:24000/mex"라고 겹치기 때문에 중간에 그것을 구분해주는 서비스 명을 넣은 것입니다.

반면에, net.tcp에서는 그냥 "net.tcp://localhost:24001/"에서 마무리 지었지요. 그 대신, 각각의 서비스마다 "endpoint" 설정을 두어서 address에 "ServiceA", "ServiceB"를 추가해 놓은 것입니다. 만약 endpoint의 address 값을 공백 문자열로 주었다면 baseAddress에서부터 서비스를 구분하는 문자열을 두어야 합니다.

마지막으로, 첨부된 파일은 위의 내용들을 반영한 간단한 예제 프로젝트입니다.



[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/28/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13332정성태4/27/20233863Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233913오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233552Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233748Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233421VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233822VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235249.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234559스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234369.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234298개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235103VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233916개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233892개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234345개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234187개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234263오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233574오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233785Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233882개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20233946개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20233972Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234473C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234081C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234240.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234146스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233897.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...