共用方式為


How to: Consume a Service

Any managed VSPackage that derives from Package and that has been correctly sited can ask itself for any global service. Because the Package class implements IServiceProvider, any VSPackage that derives from Package is also a service provider.

When Visual Studio loads a managed VSPackage, it passes an IServiceProvider service provider to the Package SetSite method during initialization, siting the VSPackage. The Package class wraps this service provider and provides the GetService method for obtaining services.

Note

Because the VSPackage constructor is called before the VSPackage is sited, global services are typically unavailable from within the VSPackage constructor. See How to: Troubleshoot Services for a workaround.

To consume a service

  • Insert this code in any method except the VSPackage constructor:

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

    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

Tasks

How to: Provide a Service

Concepts

Visual Studio Extensibility Samples

Service Essentials

Other Resources

Services