관리되는 애플리케이션 내에서 서비스를 호스트하려면 관리되는 애플리케이션 코드 내에 서비스에 대한 코드를 포함하고, 명령적으로 코드에서, 선언적으로 구성을 통해 또는 기본 엔드포인트를 사용하여 서비스에 대한 엔드포인트를 정의한 다음, 인스턴스 ServiceHost를 만듭니다.
메시지 수신을 시작하려면 ServiceHost의 Open로 전화하십시오. 이 작업은 서비스에 대한 수신기를 생성하고 엽니다. 이러한 방식으로 서비스를 호스팅하는 것은 관리되는 애플리케이션이 호스팅 작업 자체를 수행하기 때문에 종종 "자체 호스팅"이라고 합니다. 서비스를 종료하려면 CommunicationObject.Close에 ServiceHost로 전화하세요.
서비스는 관리되는 Windows 서비스, IIS(인터넷 정보 서비스) 또는 WAS(Windows Process Activation Service)에서 호스트될 수도 있습니다. 서비스에 대한 호스팅 옵션에 대한 자세한 내용은 호스팅 서비스를 참조하세요.
관리되는 애플리케이션에서 서비스를 호스팅하는 것은 배포할 인프라가 가장 적기 때문에 가장 유연한 옵션입니다. 관리되는 애플리케이션에서 서비스를 호스팅하는 방법에 대한 자세한 내용은 관리되는 애플리케이션에서 호스팅을 참조하세요.
다음 절차에서는 콘솔 애플리케이션에서 자체 호스팅 서비스를 구현하는 방법을 보여 줍니다.
자체 호스팅 서비스 만들기
새 콘솔 애플리케이션을 만듭니다.
Visual Studio를 열고 파일 메뉴에서 새>프로젝트를 선택합니다.
설치된 템플릿 목록에서 Visual C# 또는 Visual Basic을 선택한 다음, Windows Desktop을 선택합니다.
콘솔 앱 템플릿을 선택합니다. 이름 상자에 입력
SelfHost
한 다음 확인을 선택합니다.
솔루션 탐색기에서 SelfHost를 마우스 오른쪽 단추로 클릭하고 참조 추가를 선택합니다. .NET 탭에서 System.ServiceModel을 선택한 다음 확인을 선택합니다.
팁 (조언)
솔루션 탐색기 창이 표시되지 않으면 보기 메뉴에서 솔루션 탐색기를 선택합니다.
솔루션 탐색기에서 Program.cs 두 번 클릭하거나 Module1.vb 코드 창에서 엽니다(아직 열려 있지 않은 경우). 파일 맨 위에 다음 문을 추가합니다.
using System.ServiceModel; using System.ServiceModel.Description;
Imports System.ServiceModel Imports System.ServiceModel.Description
서비스 계약을 정의하고 구현합니다. 이 예제에서는
HelloWorldService
서비스에 대한 입력을 기반으로 메시지를 반환하는 값을 정의합니다.[ServiceContract] public interface IHelloWorldService { [OperationContract] string SayHello(string name); } public class HelloWorldService : IHelloWorldService { public string SayHello(string name) { return string.Format("Hello, {0}", name); } }
<ServiceContract()> Public Interface IHelloWorldService <OperationContract()> Function SayHello(ByVal name As String) As String End Interface Public Class HelloWorldService Implements IHelloWorldService Public Function SayHello(ByVal name As String) As String Implements IHelloWorldService.SayHello Return String.Format("Hello, {0}", name) End Function End Class
비고
서비스 인터페이스를 정의하고 구현하는 방법에 대한 자세한 내용은 방법: 서비스 계약 정의 및 방법: 서비스 계약 구현을 참조하세요.
Main
메서드의 맨 위에서 서비스의 기본 주소를 사용하여 Uri 클래스의 인스턴스를 만듭니다.Uri baseAddress = new Uri("http://localhost:8080/hello");
Dim baseAddress As Uri = New Uri("http://localhost:8080/hello")
ServiceHost 클래스의 인스턴스를 만들고, 서비스 유형을 나타내는 Type 및 기본 주소 URI(Uniform Resource Identifier)를 ServiceHost(Type, Uri[])에 전달합니다. 메타데이터 게시를 사용하도록 설정한 다음, 메서드 ServiceHost 를 Open 호출하여 서비스를 초기화하고 메시지를 받도록 준비합니다.
// Create the ServiceHost. using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress)) { // Enable metadata publishing. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; host.Description.Behaviors.Add(smb); // Open the ServiceHost to start listening for messages. Since // no endpoints are explicitly configured, the runtime will create // one endpoint per base address for each service contract implemented // by the service. host.Open(); Console.WriteLine($"The service is ready at {baseAddress}"); Console.WriteLine("Press <Enter> to stop the service."); Console.ReadLine(); // Close the ServiceHost. host.Close(); }
' Create the ServiceHost. Using host As New ServiceHost(GetType(HelloWorldService), baseAddress) ' Enable metadata publishing. Dim smb As New ServiceMetadataBehavior() smb.HttpGetEnabled = True smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15 host.Description.Behaviors.Add(smb) ' Open the ServiceHost to start listening for messages. Since ' no endpoints are explicitly configured, the runtime will create ' one endpoint per base address for each service contract implemented ' by the service. host.Open() Console.WriteLine("The service is ready at {0}", baseAddress) Console.WriteLine("Press <Enter> to stop the service.") Console.ReadLine() ' Close the ServiceHost. host.Close() End Using
비고
이 예제에서는 기본 엔드포인트를 사용하며 이 서비스에는 구성 파일이 필요하지 않습니다. 엔드포인트가 구성되지 않은 경우 런타임은 서비스에서 구현하는 각 서비스 계약의 각 기본 주소에 대해 하나의 엔드포인트를 만듭니다. 기본 엔드포인트에 대한 자세한 내용은 WCF 서비스에 대한 간소화된 구성 및 간소화된 구성을 참조하세요.
Ctrl+Shift+B를 눌러 솔루션을 빌드합니다.
서비스 테스트
Ctrl+F5 키를 눌러 서비스를 실행합니다.
WCF 테스트 클라이언트를 엽니다.
팁 (조언)
WCF 테스트 클라이언트를 열려면 Visual Studio용 개발자 명령 프롬프트를 열고 WcfTestClient.exe실행합니다.
파일 메뉴에서 서비스 추가를 선택합니다.
주소 상자에 입력
http://localhost:8080/hello
하고 확인을 클릭합니다.팁 (조언)
서비스가 실행 중인지 아니면 이 단계가 실패하는지 확인합니다. 코드에서 기본 주소를 변경한 경우 이 단계에서 수정된 기본 주소를 사용합니다.
내 서비스 프로젝트 노드에서 SayHello를 두 번 클릭합니다. 요청 목록의 값 열에 이름을 입력하고 호출을 클릭합니다.
응답 목록에 회신 메시지가 나타납니다.
예시
다음 예제에서는 HelloWorldService
유형의 서비스를 호스트하는 ServiceHost 객체를 생성하고, 이어서 ServiceHost에서 Open 메서드를 호출합니다. 기본 주소는 코드에 제공되고 메타데이터 게시는 사용하도록 설정되며 기본 엔드포인트가 사용됩니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace SelfHost
{
[ServiceContract]
public interface IHelloWorldService
{
[OperationContract]
string SayHello(string name);
}
public class HelloWorldService : IHelloWorldService
{
public string SayHello(string name)
{
return string.Format("Hello, {0}", name);
}
}
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8080/hello");
// Create the ServiceHost.
using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
{
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
// Open the ServiceHost to start listening for messages. Since
// no endpoints are explicitly configured, the runtime will create
// one endpoint per base address for each service contract implemented
// by the service.
host.Open();
Console.WriteLine($"The service is ready at {baseAddress}");
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
// Close the ServiceHost.
host.Close();
}
}
}
}
Imports System.ServiceModel
Imports System.ServiceModel.Description
Module Module1
<ServiceContract()>
Public Interface IHelloWorldService
<OperationContract()>
Function SayHello(ByVal name As String) As String
End Interface
Public Class HelloWorldService
Implements IHelloWorldService
Public Function SayHello(ByVal name As String) As String Implements IHelloWorldService.SayHello
Return String.Format("Hello, {0}", name)
End Function
End Class
Sub Main()
Dim baseAddress As Uri = New Uri("http://localhost:8080/hello")
' Create the ServiceHost.
Using host As New ServiceHost(GetType(HelloWorldService), baseAddress)
' Enable metadata publishing.
Dim smb As New ServiceMetadataBehavior()
smb.HttpGetEnabled = True
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
host.Description.Behaviors.Add(smb)
' Open the ServiceHost to start listening for messages. Since
' no endpoints are explicitly configured, the runtime will create
' one endpoint per base address for each service contract implemented
' by the service.
host.Open()
Console.WriteLine("The service is ready at {0}", baseAddress)
Console.WriteLine("Press <Enter> to stop the service.")
Console.ReadLine()
' Close the ServiceHost.
host.Close()
End Using
End Sub
End Module
참고하십시오
- Uri
- AppSettings
- ConfigurationManager
- 방법: IIS에서 WCF 서비스 호스트
- 셀프 호스팅
- 호스팅 서비스
- 방법: 서비스 계약 정의
- 방법: 서비스 계약 구현
- ServiceModel 메타데이터 유틸리티 도구(Svcutil.exe)
- #B0 바인딩을 사용하여 서비스를 구성하고 클라이언트를 #C1 설정
- System-Provided 바인딩