Compartilhar via


How to: Use GetGlobalService

Sometimes you may need to get a service from a tool window or control container that has not been sited, or else has been sited with a service provider that does not know about the service you want. For example, you might want to write to the activity log from within a control. For more information about these and other scenarios, see How to: Troubleshoot Services.

You can get most Visual Studio services by calling the static GetGlobalService method.

GetGlobalService relies on a cached service provider that is initialized the first time any VSPackage derived from Package is sited. You must guarantee that this condition is met, or else be prepared for a null service.

Fortunately, GetGlobalService works correctly most of the time.

  • If a VSPackage provides a service known only to another VSPackage, the VSPackage requesting the service is sited before the VSPackage providing the service is loaded.

  • If a tool window is created by a VSPackage, the VSPackage is sited before the tool window is created.

  • If a control container is hosted by a tool window created by a VSPackage, the VSPackage is sited before the control container is created.

To get a service from within a tool window or control container

  • Insert this code in the constructor, tool window, or control container:

    IVsActivityLog log = Package.GetGlobalService(typeof(SVsActivityLog)) as IVsActivityLog;
    if (log == null) return;
    
    Dim log As IVsActivityLog = TryCast(Package.GetGlobalService(GetType(SVsActivityLog)), IVsActivityLog)
    If log Is Nothing Then
        Return
    End If
    

    This code obtains an SVsActivityLog service and casts it to an IVsActivityLog interface, which can be used to write to the activity log. For an example, see How to: Use the Activity Log.

See Also

How to: Troubleshoot Services
Using and Providing Services
Service Essentials