컨테이너와 구성 요소 간 통신

컨테이너는 클라이언트 응용 프로그램과 여기에 포함된 구성 요소 사이의 통신 장소입니다. 구성 요소의 실제 이름이나 ID를 몰라도 응용 프로그램에서는 컨테이너 안의 구성 요소에 대한 참조를 얻을 수 있습니다. 또한 구성 요소는 컨테이너를 통해 다양한 방법으로 클라이언트 응용 프로그램과 상호 작용할 수 있습니다.

컨테이너 개체는 Components 속성을 통해 컨테이너의 구성 요소를 노출합니다. 이 속성은 IComponent 참조 개체를 반환하는 인덱싱된 속성입니다. 구성 요소는 선입선출 방식으로 추적되며 다음과 같은 구문을 사용하여 인덱스를 통해 액세스할 수 있습니다.

Imports System.ComponentModel
Dim MyContainer As Container
Dim xComponent as IComponent
xComponent = MyContainer.Components(0)
using System.ComponentModel;
Container MyContainer = new Container();
IComponent xComponent;
xComponent = MyContainer.Components[0];

이름을 사용하지 않고도 컨테이너에 구성 요소를 추가할 수 있습니다. 참조하는 구성 요소의 이름을 알고 있는 경우 다음 예제와 같이 이 이름을 사용하여 컨테이너를 통해 참조를 얻을 수 있습니다.

xComponent = MyContainer.Components("myComponent")
xComponent = MyContainer.Components["myComponent"];

Components 속성은 IComponent 참조를 반환하며 해당 인터페이스에 의해 구현되지 않은 구성 요소의 메서드와 속성에 액세스할 수 없다는 점에 유의하십시오.

구성 요소는 주로 해당 구성 요소의 Site 속성을 통해 컨테이너와 통신합니다. 구성 요소에서는 다음과 같이 Site를 통해 컨테이너에서 구현된 IContainer 인터페이스에 대한 참조를 얻을 수 있습니다.

Dim myComponent As New Component()
Dim myIContainer as IContainer
myIContainer = myComponent.Site.Container
Component myComponent = new Component();
IContainer myIContainer;
myIContainer = myComponent.Site.Container;

Container 속성에서도 동일한 참조가 반환됩니다. 이것은 바로 가기로 간주할 수 있습니다. 참조는 ISite 개체를 통해 계속 제공되지만 이 경우에는 명시적으로 제공되지 않습니다.

또한 구성 요소에서 IServiceProvider.GetService 메서드를 호출하여 컨테이너가 제공되는 경우 해당 컨테이너로부터 서비스를 얻을 수도 있습니다. 이 메서드는 다음과 같이 지정된 형식의 개체를 반환합니다.

Dim myComponent As Component
Dim myWidget As Widget
Dim serviceObject As Object
' This returns an object of type Widget that is supplied by the container.
serviceObject = myComponent.Site.GetService(GetType(Widget))
myWidget = CType(serviceObject, Widget)
Component myComponent = new Component();
Widget myWidget;
object serviceObject;
// This returns an object of type Widget that is supplied by the container.
serviceObject = myComponent.Site.GetService(System.Type.GetType("CommunicateCS.Widget"));
myWidget = (Widget)serviceObject;

GetService를 통해 개체를 가져오려면 상속된 컨테이너 클래스에서 이와 같이 구현되어 있어야 합니다. 즉, Container 클래스의 GetService 메서드가 재정의되고 서비스 개체를 제공하는 코드가 구현되어야 합니다.

참고 항목

작업

방법: 구성 요소 컨테이너 만들기

방법: 구성 요소 컨테이너 확장

개념

컨테이너, 사이트 및 구성 요소