Communication Between Containers and Components
A container is a nexus for communication between the client application and the components it contains. An application may obtain references to components within the container without knowing the actual name or identity of the component. The component may also interact with the client application through the container in a variety of ways.
The container object exposes the components it contains through its Components property. This property is an indexed property that returns an IComponent reference object. Components are tracked on a first-in, first-out basis, and are accessible through the index using the following syntax:
using System.ComponentModel; Container MyContainer = new Container(); IComponent xComponent; xComponent = MyContainer.Components;
Components may be added to a container with or without a name. If you know the name of the component you are referring to, you may also get the reference through the container using that name, as shown in the following example:
The component communicates with the container primarily through its Site property. Through Site, the component can obtain a reference to the IContainer interface implemented by the container, as shown below:
Component myComponent = new Component(); IContainer myIContainer; myIContainer = myComponent.Site.Container;
The component can also get services from the container (if they are supplied) by calling IServiceProvider.GetService Method. This method returns an object of the specified type, as shown below:
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;
In order to receive an object via GetService, it must be implemented in an inherited container class. The GetService method of the Container class should be overridden and code to supply the service object implemented.